http工具类_http请求工具类 - CSDN
  • HttpUtil工具类

    2019-07-15 16:41:15
    代码: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream;...import java.net.HttpURLConnection;...import java.net....

    代码:

    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.List;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    import org.apache.log4j.Logger;
    import org.codehaus.jettison.json.JSONException;
    import org.codehaus.jettison.json.JSONObject;
    
    public class HttpUtils {
        static Logger logger = Logger.getLogger(HttpUtils.class);
    
        public static JSONObject httpGet(String urlStr) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    
            StringBuffer buf = new StringBuffer();
            String inputLine = in.readLine();
            while (inputLine != null) {
                buf.append(inputLine).append("\r\n");
                inputLine = in.readLine();
            }
            in.close();
            //
            return new JSONObject(buf.toString().trim());
        }
    
        public static String httpGet1(String urlStr) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    
            StringBuffer buf = new StringBuffer();
            String inputLine = in.readLine();
            while (inputLine != null) {
                buf.append(inputLine).append("\r\n");
                inputLine = in.readLine();
            }
            in.close();
            //
            return buf.toString().trim();
        }
    
        public static String httpGet2(String urlStr) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    
            StringBuffer buf = new StringBuffer();
            String inputLine = in.readLine();
            while (inputLine != null) {
                buf.append(inputLine).append("\r\n");
                inputLine = in.readLine();
            }
            in.close();
            //
            return buf.toString().trim();
        }
    
        public static String httpPut(String urlStr) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            int code = conn.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            logger.error("code=" + conn.getResponseCode());
            StringBuffer buf = new StringBuffer();
            String inputLine = in.readLine();
            while (inputLine != null) {
                buf.append(inputLine).append("\r\n");
                inputLine = in.readLine();
            }
            in.close();
            //
            return (buf.toString().trim()) != null ? (buf.toString().trim()) : (code + "");
        }
    
        public static JSONObject httpPost(String urlStr) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    
            StringBuffer buf = new StringBuffer();
            String inputLine = in.readLine();
            while (inputLine != null) {
                buf.append(inputLine).append("\r\n");
                inputLine = in.readLine();
            }
            in.close();
            //
            return new JSONObject(buf.toString().trim());
        }
    
        public static JSONObject httpPost(String urlStr, String postText) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            byte[] bytes = postText.getBytes("utf-8");
            OutputStream os = conn.getOutputStream();
            os.write(bytes);
            os.close();
            //
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
            StringBuffer buf = new StringBuffer();
            String inputLine = in.readLine();
            while (inputLine != null) {
                buf.append(inputLine).append("\r\n");
                //
                inputLine = in.readLine();
            }
            in.close();
            //
            return new JSONObject(buf.toString().trim());
        }
    
        public static Object post(List<NameValuePair> message, String to)
                throws ParseException, IOException, JSONException {
    
            HttpPost post = new HttpPost(to);
            UrlEncodedFormEntity params = new UrlEncodedFormEntity(message, "UTF-8");
            post.setEntity(params);
            System.out.println(("[] Post \"" + message + "\" to " + post.getURI()));
            CloseableHttpClient client = HttpClients.createDefault();
            CloseableHttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("[] Server Status Code: " + statusCode);
    
            String respString = null;
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                respString = EntityUtils.toString(entity, "UTF-8");
            }
            System.out.println("[] Server return: " + respString);
            EntityUtils.consume(entity);
    
            JSONObject result = new JSONObject(respString.trim());
            if (result != null && result.has("success") && result.opt("success").equals("true")) {
                return result.opt("data");
            } else {
                logger.info(message);
                return "error";
            }
        }
    
        public static String httpPostApplication(String urlStr) throws Exception {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    
            StringBuffer buf = new StringBuffer();
            String inputLine = in.readLine();
            while (inputLine != null) {
                buf.append(inputLine).append("\r\n");
                inputLine = in.readLine();
            }
            in.close();
            //
            return buf.toString().trim();
        }
    
        public static String RestfulGet(String url) {
            String returnString = "";
            try {
                URL restServiceURL = new URL(url);
                HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
                httpConnection.setRequestMethod("GET");
                httpConnection.setRequestProperty("Accept", "application/json");
                httpConnection.setRequestProperty("Accept-Charset", "utf-8");
                httpConnection.setRequestProperty("contentType", "utf-8");
                if (httpConnection.getResponseCode() != 200) {
                    throw new RuntimeException(
                            "HTTP GET Request Failed with Error code : " + httpConnection.getResponseCode());
                }
                BufferedReader responseBuffer = new BufferedReader(
                        new InputStreamReader((httpConnection.getInputStream()), "utf-8"));
                String output = responseBuffer.readLine();
                // System.out.println("Output from Server: \n");
                StringBuffer buf = new StringBuffer();
                while (output != null) {
                    buf.append(output).append("\r\n");
                    output = responseBuffer.readLine();
                }
                responseBuffer.close();
                httpConnection.disconnect();
                returnString = buf.toString().trim();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return returnString;
        }
    
        public static String RestfulPost(String url, String input) {
            String result = "";
            try {
                URL targetUrl = new URL(url);
                HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
                httpConnection.setDoOutput(true);
                httpConnection.setRequestMethod("POST");
                httpConnection.setRequestProperty("Charsert", "UTF-8");
                httpConnection.setRequestProperty("Content-Type", "application/json");
                OutputStream outputStream = httpConnection.getOutputStream();
                outputStream.write(input.getBytes());
                outputStream.flush();
                if (httpConnection.getResponseCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : " + httpConnection.getResponseCode());
                }
                BufferedReader responseBuffer = new BufferedReader(
                        new InputStreamReader((httpConnection.getInputStream()), "UTF-8"));
                String output;
                System.out.println("Output from Server:\n");
                StringBuffer buf = new StringBuffer();
                while ((output = responseBuffer.readLine()) != null) {
                    buf.append(output).append("\r\n");
                }
                httpConnection.disconnect();
                responseBuffer.close();
                result = buf.toString().trim();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
    
        }
    
        public static org.codehaus.jettison.json.JSONObject post(net.sf.json.JSONObject json, String to)
                throws ParseException, IOException, JSONException {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(to);
            post.setHeader("Content-Type", "application/json");
            org.codehaus.jettison.json.JSONObject result = null;
            java.io.InputStream inStream = null;
            try {
                StringEntity s = new StringEntity(json.toString(), "utf-8");
                s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(s);
                // 发送请求
                HttpResponse httpResponse = client.execute(post);
                // 获取响应输入流
                inStream = httpResponse.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strber.append(line + "\n");
                }
                inStream.close();
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    result = new org.codehaus.jettison.json.JSONObject(strber.toString());
                } else {
                    logger.error("请求服务端失败" + json);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
        public static net.sf.json.JSONObject doPutOrPost(String type, String urlString, net.sf.json.JSONObject jsonObject,
                String callMethed) {
            try {
                String result = "";
                String info = callMethed + ",调用SDK的restful接口URL:" + urlString + ",请求参数:" + jsonObject.toString() + ",请求方式:"
                        + type;
                logger.info(info);
                URL url = new URL(urlString);
                int code = 0;
                // 打开restful链接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 提交模式
                conn.setRequestMethod(type);
                conn.setConnectTimeout(200000);// 连接超时 单位毫秒
                conn.setReadTimeout(200000);// 读取超时 单位毫秒
                conn.setDoOutput(true);// 是否输入参数
                conn.setDoInput(true);
                // 设置访问提交模式,表单提交
                conn.setRequestProperty("Content-Type", "application/json");
                // 设置请求头
                // conn.setRequestProperty(SDKKeyName, SDKKey);
                // conn.setRequestProperty(SDKValueName, SDKValue);
                // ----------------传入数据----------------------
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(jsonObject.toString().getBytes());
                code = conn.getResponseCode();
                outputStream.flush();
                // 判断是否创建成功
                logger.info(info + ",调用所得code值为:" + code);
                System.out.println("---------code=" + code);
                if (code == 200) {// 执行成功
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                    StringBuffer buffer = new StringBuffer();
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line);
                    }
                    reader.close();
                    result = buffer.toString();
                    logger.info(info + ",调用结果信息为:" + result);
                    net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(result);
                    return jsonObj;
                } else {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"));
                    StringBuffer buffer = new StringBuffer();
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line);
                    }
                    reader.close();
                    result = buffer.toString();
                    logger.info(info + ",调用结果信息为:" + result);
                    net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(result);
                    return jsonObj;
    
                }
            } catch (Exception e) {
                logger.error("请求失败", e);
                return null;
            }
        }
    
        public static int intOf(Object obj, int initValue) {
            // 1.判断参数是否合法
            if (obj == null || "".equals(obj)) {
                return initValue;
            } else {
                try {
                    return Integer.parseInt(obj.toString());
                } catch (Exception e) {
                    e.getMessage();
                    return initValue;
                }
            }
        }
    }

     

    展开全文
  • http工具类

    2018-06-13 11:01:37
    java
    封装好的http工具类,方便以后使用
    1. package com.wzm.util;  
    2.   
    3. import java.io.BufferedReader;  
    4. import java.io.IOException;  
    5. import java.io.InputStreamReader;  
    6. import java.net.URI;  
    7. import java.util.ArrayList;  
    8. import java.util.Iterator;  
    9. import java.util.List;  
    10. import java.util.Map;  
    11.   
    12. import org.apache.http.HttpEntity;  
    13. import org.apache.http.HttpResponse;  
    14. import org.apache.http.HttpStatus;  
    15. import org.apache.http.NameValuePair;  
    16. import org.apache.http.StatusLine;  
    17. import org.apache.http.client.HttpClient;  
    18. import org.apache.http.client.entity.UrlEncodedFormEntity;  
    19. import org.apache.http.client.methods.CloseableHttpResponse;  
    20. import org.apache.http.client.methods.HttpGet;  
    21. import org.apache.http.client.methods.HttpPost;  
    22. import org.apache.http.entity.StringEntity;  
    23. import org.apache.http.impl.client.CloseableHttpClient;  
    24. import org.apache.http.impl.client.DefaultHttpClient;  
    25. import org.apache.http.impl.client.HttpClients;  
    26. import org.apache.http.message.BasicNameValuePair;  
    27. import org.apache.http.protocol.HTTP;  
    28. import org.apache.http.util.EntityUtils;  

    29. public class HttpUtil {  
    30.       
    31.     private static Logger logger = Logger.getLogger(HttpUtil.class);  
    32.   
    33.     /** 
    34.      * get请求 
    35.      * @return 
    36.      */  
    37.     public static String doGet(String url) {  
    38.         try {  
    39.             HttpClient client = new DefaultHttpClient();  
    40.             //发送get请求  
    41.             HttpGet request = new HttpGet(url);  
    42.             HttpResponse response = client.execute(request);  
    43.    
    44.             /**请求发送成功,并得到响应**/  
    45.             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
    46.                 /**读取服务器返回过来的json字符串数据**/  
    47.                 String strResult = EntityUtils.toString(response.getEntity());  
    48.                   
    49.                 return strResult;  
    50.             }  
    51.         }   
    52.         catch (IOException e) {  
    53.             e.printStackTrace();  
    54.         }  
    55.           
    56.         return null;  
    57.     }  
    58.       
    59.     /** 
    60.      * post请求(用于key-value格式的参数) 
    61.      * @param url 
    62.      * @param params 
    63.      * @return 
    64.      */  
    65.     public static String doPost(String url, Map params){  
    66.           
    67.         BufferedReader in = null;    
    68.         try {    
    69.             // 定义HttpClient    
    70.             HttpClient client = new DefaultHttpClient();    
    71.             // 实例化HTTP方法    
    72.             HttpPost request = new HttpPost();    
    73.             request.setURI(new URI(url));  
    74.               
    75.             //设置参数  
    76.             List<NameValuePair> nvps = new ArrayList<NameValuePair>();   
    77.             for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {  
    78.                 String name = (String) iter.next();  
    79.                 String value = String.valueOf(params.get(name));  
    80.                 nvps.add(new BasicNameValuePair(name, value));  
    81.             }  
    82.             request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));  
    83.               
    84.             HttpResponse response = client.execute(request);    
    85.             int code = response.getStatusLine().getStatusCode();  
    86.             if(code == 200){    //请求成功  
    87.                 in = new BufferedReader(new InputStreamReader(response.getEntity()    
    88.                         .getContent(),"utf-8"));  
    89.                 StringBuffer sb = new StringBuffer("");    
    90.                 String line = "";    
    91.                 String NL = System.getProperty("line.separator");    
    92.                 while ((line = in.readLine()) != null) {    
    93.                     sb.append(line + NL);    
    94.                 }  
    95.                   
    96.                 in.close();    
    97.                   
    98.                 return sb.toString();  
    99.             }  
    100.             else{   //  
    101.                 System.out.println("请求失败,状态码:" + code);  
    102.                 return null;  
    103.             }  
    104.         }  
    105.         catch(Exception e){  
    106.             e.printStackTrace();  
    107.               
    108.             return null;  
    109.         }  
    110.     }  
    111.       
    112.     /** 
    113.      * post请求(用于请求json格式的参数) 
    114.      * @param url 
    115.      * @param params 
    116.      * @return 
    117.      */  
    118.     public static String doPost(String url, String params) throws Exception {  
    119.           
    120.         CloseableHttpClient httpclient = HttpClients.createDefault();  
    121.         HttpPost httpPost = new HttpPost(url);// 创建httpPost     
    122.         httpPost.setHeader("Accept""application/json");   
    123.         httpPost.setHeader("Content-Type""application/json");  
    124.         String charSet = "UTF-8";  
    125.         StringEntity entity = new StringEntity(params, charSet);  
    126.         httpPost.setEntity(entity);          
    127.         CloseableHttpResponse response = null;  
    128.           
    129.         try {  
    130.               
    131.             response = httpclient.execute(httpPost);  
    132.             StatusLine status = response.getStatusLine();  
    133.             int state = status.getStatusCode();  
    134.             if (state == HttpStatus.SC_OK) {  
    135.                 HttpEntity responseEntity = response.getEntity();  
    136.                 String jsonString = EntityUtils.toString(responseEntity);  
    137.                 return jsonString;  
    138.             }  
    139.             else{  
    140.            
    141.                 System.out.println("请求返回:"+state+"("+url+")");
    142.             }  
    143.         }  
    144.         finally {  
    145.             if (response != null) {  
    146.                 try {  
    147.                     response.close();  
    148.                 } catch (IOException e) {  
    149.                     e.printStackTrace();  
    150.                 }  
    151.             }  
    152.             try {  
    153.                 httpclient.close();  
    154.             } catch (IOException e) {  
    155.                 e.printStackTrace();  
    156.             }  
    157.         }  
    158.         return null;  
    159.     }  
    160.       
    161. }  
    展开全文
  • HTTPClient工具类,完整

    2020-07-29 14:20:11
    HTTPClient工具类,完整,HTTPClient工具类,完整,HTTPClient工具类,完整HTTPClient工具类,完整,HTTPClient工具类,完整
  • Http工具类

    2019-11-11 14:23:48
    网络请求在安卓开发中非常常见,写一个工具类能有效的节省开发时间提高效率,这里就分享一下,有不足的请斧正 引入 implementation("com.squareup.okhttp3:okhttp:4.2.1") 需要的权限 <uses-permission ...

    网络请求在安卓开发中非常常见,写一个工具类能有效的节省开发时间提高效率,这里就分享一下,有不足的请斧正

    引入

    implementation("com.squareup.okhttp3:okhttp:4.2.1")

    需要的权限

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

    Kotlin版本

    import android.os.Environment
    import com.epuxun.drink.utli.application
    import okhttp3.*
    import okhttp3.MediaType.Companion.toMediaType
    import okhttp3.RequestBody.Companion.asRequestBody
    import okhttp3.RequestBody.Companion.toRequestBody
    import okio.BufferedSink
    import java.io.BufferedInputStream
    import java.io.File
    import java.io.IOException
    import java.util.*
    import java.util.concurrent.TimeUnit
    
    object HttpHelper {
    
        private const val MEDIA_TYPE = "application/json; charset=utf-8"
    
        private const val MAX_CACHE_SIZE = 1024 * 1024 * 50L// 50M 的缓存大小
    
        private const val DEFAULT_TIMEOUT = 15L
    
        /**
         * 获取 OkHttpClient
         */
        private fun getOkHttpClient(): OkHttpClient {
            val builder = OkHttpClient().newBuilder()
            val cacheFile = File(application.cacheDir, "cache")
            val cache = Cache(cacheFile, MAX_CACHE_SIZE)
    
            builder.run {
                cache(cache)//设置 请求的缓存的大小跟位置
                connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                readTimeout(DEFAULT_TIMEOUT, TimeUnit.MINUTES)
                writeTimeout(DEFAULT_TIMEOUT, TimeUnit.MINUTES)
                retryOnConnectionFailure(true)
            }
    
            return builder.build()
        }
    
        /**
         * 获取键值对FormBody.Builder
         */
        fun getBuilder(): FormBody.Builder {
            return FormBody.Builder()
        }
    
        /**
         * post方式提交键值对
         * 参数1:[url] url ,参数2:[body] 键值对
         * 返回 可空字符串
         */
        @Throws(IOException::class)
        fun post(url: String, body: RequestBody): String {
            val request = Request.Builder()
                .url(url)
                .post(body)
                .build()
            val response = getOkHttpClient().newCall(request).execute()
            val responseBody = response.body
            return responseBody?.string() ?: ""
        }
    
        /**
         * post方式提交json字符串
         * 参数1:[url] url,参数2:[json] json字符串
         * 返回可空字符串
         */
        @Throws(IOException::class)
        fun post(url: String, json: String): String {
            ///okHttp4 拓展功能(Kotlin)
            ///String.toMediaType()替换MediaType.get(String),需要导入import okhttp3.MediaType.Companion.toMediaType
            ///String.toRequestBody(MediaType)替换RequestBody.create(String,MediaType),import okhttp3.RequestBody.Companion.toRequestBody
            return post(
                url,
                json.toRequestBody(MEDIA_TYPE.toMediaType())
            )
        }
    
        /**
         * post方式提交流
         * 参数1:[url] url,参数2:[bis] 缓冲字节流
         * 返回可空字符串
         */
        @Throws(IOException::class)
        fun post(url: String, bufferedInputStream: BufferedInputStream): String {
            val body = object : RequestBody() {
                override fun writeTo(sink: BufferedSink) {
                    try {
                        bufferedInputStream.use { bis ->
                            sink.outputStream().buffered().use { bos ->
                                bis.copyTo(bos)
                            }
                        }
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
    
                override fun contentType(): MediaType {
                    return MEDIA_TYPE.toMediaType()
                }
    
            }
            return post(url, body)
        }
    
        /**
         * post方式提交文件
         * 参数1:[url] url,参数2:[file] 文件
         * 返回可空字符串
         */
        @Throws(IOException::class)
        fun post(url: String, file: File): String {
            //okHttp4 拓展功能
            //file.asRequestBody需要import okhttp3.RequestBody.Companion.asRequestBody
            //替换RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), file)
            return post(
                url,
                file.asRequestBody("text/x-markdown; charset=utf-8".toMediaType())
            )
        }
    
        /**
         * Post方式提交分块请求,可以上传多个文件
         * 参数1:[imageUrl] url,参数2:[file] 多个文件
         * 返回可空字符串
         */
        @Throws(IOException::class)
        fun post(url: String, vararg files: File): String {
            val requestBody = MultipartBody.Builder()
                //设置分块提交模式
                .setType(MultipartBody.FORM)
                //分块提交,标题
                .addFormDataPart("title", "block")
    
            for (file in files) {
                requestBody.addFormDataPart(
                    file.name,
                    file.name,
                    file.asRequestBody("image/png".toMediaType())
                )
            }
    
            return post(url, requestBody.build())
        }
    
        /**
         * post方式提交键值对
         * 参数1:[url] url ,参数2:[body] 键值对
         * 返回字符串,如果数据为空抛出空指针异常
         */
        @Throws(IOException::class)
        fun get(url: String): String {
            val request = Request.Builder()
                .url(url)
                .build()
    
            val response = getOkHttpClient().newCall(request).execute()
            val responseBody = response.body
            return responseBody?.string() ?: ""
        }
    
        /**
         * 下载文件
         * 参数1:[url] 文件url,参数2:[file] 保存到指定目录
         * 必须在线程中调用,不然主线程会卡住,返回是否下载成功布尔值
         */
        fun downloadFile(url: String, file: File): Boolean {
            val request = Request.Builder()
                .url(url)
                .build()
    
            try {
                getOkHttpClient().newCall(request).execute().body?.run {
                    file.outputStream().buffered().use { bos ->
                        this.byteStream().buffered().use { bis ->
                            bis.copyTo(bos)
                            return true
                        }
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
    
            return false
        }
    
        /**
         * 顺序下载
         * 需要参数:url
         * 必须在线程中调用,不然主线程会卡住,返回是否下载成功布尔值
         */
        fun sequentialDownload(vararg urls: String): Boolean {
            //失败次数
            var failure = 0
    
            for (url in urls) {
                if (failure == 3) {
                    return false
                }
                val fileNames = url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                if (fileNames.isNotEmpty()) {
                    val file =
                        createFilePath(fileNames[fileNames.size - 1])
                    if (downloadFile(url, file)) {
                        failure = 0
                    } else {
                        failure++
                    }
                }
            }
            return true
        }
    
        /**
         * 创建文件路径
         */
        fun createFilePath(fileName: String): File {
            val path = Objects.requireNonNull<File>(application.getExternalFilesDir(Environment.DIRECTORY_PICTURES))
                    .absolutePath
            val file = File(path, fileName)
            //如果有同名文件则删除
            if (file.exists()) {
                file.delete()
            }
            file.createNewFile()
            return file
        }
    }

     

    展开全文
  • Http工具类 HttpUtils

    2019-05-09 17:08:51
    import java.io.IOException; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.N....
    import java.io.IOException;
    import java.nio.charset.Charset;
    import java.security.KeyManagementException;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import javax.net.ssl.SSLContext;
    
    import com.alibaba.fastjson.JSONObject;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.config.ConnectionConfig;
    import org.apache.http.config.Registry;
    import org.apache.http.config.RegistryBuilder;
    import org.apache.http.config.SocketConfig;
    import org.apache.http.conn.socket.ConnectionSocketFactory;
    import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
    import org.apache.http.conn.socket.PlainConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLContexts;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    /**
     * <p>类名: HttpUtils</p>
     * <p>描述: http请求工具类</p>
     * <p>修改时间: 2019年04月30日 上午10:12:35</p>
     *
     * @author lidongyang
     */
    public class HttpUtils {
    
        public static String defaultEncoding = "utf-8";
    
        /**
         * 发送http post请求,并返回响应实体
         *
         * @param url 请求地址
         * @return url响应实体
         */
        public static String postRequest(String url) {
            return postRequest(url, null, null);
        }
    
        /**
         * <p>方法名: postRequest</p>
         * <p>描述: 发送httpPost请求</p>
         *
         * @param url
         * @param params
         * @return
         */
        public static String postRequest(String url, Map<String, Object> params) {
            return postRequest(url, null, params);
        }
    
        /**
         * 发送http post请求,并返回响应实体
         *
         * @param url     访问的url
         * @param headers 请求需要添加的请求头
         * @param params  请求参数
         * @return
         */
        public static String postRequest(String url, Map<String, String> headers,
                                         Map<String, Object> params) {
            String result = null;
            CloseableHttpClient httpClient = buildHttpClient();
            HttpPost httpPost = new HttpPost(url);
    
            if (null != headers && headers.size() > 0) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    httpPost.addHeader(new BasicHeader(key, value));
                }
            }
            if (null != params && params.size() > 0) {
                List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
                    pairList.add(pair);
                }
                httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(defaultEncoding)));
            }
    
            try {
                CloseableHttpResponse response = httpClient.execute(httpPost);
                try {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        result = EntityUtils.toString(entity,
                                Charset.forName(defaultEncoding));
                    }
                } finally {
                    response.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return result;
        }
    
        /**
         * 发送http get请求
         *
         * @param url 请求url
         * @return url返回内容
         */
        public static String getRequest(String url) {
            return getRequest(url, null);
        }
    
    
        /**
         * 发送http get请求
         *
         * @param url    请求的url
         * @param params 请求的参数
         * @return
         */
        public static String getRequest(String url, Map<String, Object> params) {
            return getRequest(url, null, params);
        }
    
        /**
         * 发送http get请求
         *
         * @param url        请求的url
         * @param headersMap 请求头
         * @param params     请求的参数
         * @return
         */
        public static String getRequest(String url, Map<String, String> headersMap, Map<String, Object> params) {
            String result = null;
            CloseableHttpClient httpClient = buildHttpClient();
            try {
                String apiUrl = url;
                if (null != params && params.size() > 0) {
                    StringBuffer param = new StringBuffer();
                    int i = 0;
                    for (String key : params.keySet()) {
                        if (i == 0)
                            param.append("?");
                        else
                            param.append("&");
                        param.append(key).append("=").append(params.get(key));
                        i++;
                    }
                    apiUrl += param;
                }
    
                HttpGet httpGet = new HttpGet(apiUrl);
                if (null != headersMap && headersMap.size() > 0) {
                    for (Entry<String, String> entry : headersMap.entrySet()) {
                        String key = entry.getKey();
                        String value = entry.getValue();
                        httpGet.addHeader(new BasicHeader(key, value));
                    }
                }
                CloseableHttpResponse response = httpClient.execute(httpGet);
                try {
                    HttpEntity entity = response.getEntity();
                    if (null != entity) {
                        result = EntityUtils.toString(entity, defaultEncoding);
                    }
                } finally {
                    response.close();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * 创建httpclient
         *
         * @return
         */
        public static CloseableHttpClient buildHttpClient() {
            try {
                RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder
                        .create();
                ConnectionSocketFactory factory = new PlainConnectionSocketFactory();
                builder.register("http", factory);
                KeyStore trustStore = KeyStore.getInstance(KeyStore
                        .getDefaultType());
                SSLContext context = SSLContexts.custom().useTLS()
                        .loadTrustMaterial(trustStore, new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain,
                                                     String authType) throws CertificateException {
                                return true;
                            }
                        }).build();
                LayeredConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(
                        context,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                builder.register("https", sslFactory);
                Registry<ConnectionSocketFactory> registry = builder.build();
                PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
                        registry);
                ConnectionConfig connConfig = ConnectionConfig.custom()
                        .setCharset(Charset.forName(defaultEncoding)).build();
                SocketConfig socketConfig = SocketConfig.custom()
                        .setSoTimeout(100000).build();
                manager.setDefaultConnectionConfig(connConfig);
                manager.setDefaultSocketConfig(socketConfig);
                return HttpClientBuilder.create().setConnectionManager(manager)
                        .build();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return null;
        }
    
        public static void main(String[] args) {
            String url = "http://127.0.0.1:8080/user/login";
           
            JSONObject params = new JSONObject();
            params.put("username", "test");
            params.put("password", "123456");
    
            String result = HttpUtils.postRequest(url, params);
            System.out.println(result);
        }
    
    
    }

     

    展开全文
  • http请求工具类

    2018-11-23 16:32:28
    public class HttpClientUtil { private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); public static String doGet(String url, Map&lt;String, String&...
  • HTTP工具类

    2019-03-21 14:55:36
    /* * Copyright (C) 2018 All rights reserved. * * Created by gaoxing on 2018/11/28. */ package com.missfresh.antispam.sdk.utils; import java.io.IOException;...import java.io.InputStream;...import ja...
  • JAVA -----HTTP工具类

    2017-03-14 11:47:21
    package cn.zhangheng;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL;...import java.net.URLConnection;...import
  • cocos creator http工具类

    2017-05-10 10:27:37
    直接上代码 复制项目直接可用 ...我将官方文档中的http 用js 单利的模式 改了下  var httpUtils = cc.Class({ extends: cc.Component, properties: { // foo: { // default: null, // The default value will be
  • 在项目开发中,经常用调用http接口,下面是封装apache的httpclient工具类。 二、样例代码: package org.egg.utils; import org.apache.http.client.config.RequestConfig; import org.apach...
  • 前不久写了几篇有关微信定制开发的文章并整理成了专题,里面所有的文档都提到了CommonUtil这个工具类,关于这个工具类原本有写但是不是每篇博客都有,所以就有人找我要这个工具类,评论里也有好多人说不知道这个工具...
  • 现在大多数的http请求都是使用 restful 风格,系统之间的交流也是使用 restful 风格的http请求,所以就写了一个工具类来简化这些工作。 点击查看工具类代码 这个工具类是基于 HttpURLConnection 写的。 并...
  • 转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自【张鸿洋的博客】打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于...
  • 封装一个简单的Http请求工具类,主要方便设置代理请求,无需额外框架 1、需要引入的jar包 <!-- 简化代码getter setter --> <dependency> <groupId>org.projectlombok</groupId> <...
  • 在业务预约和后勤报修项目中,登录模块经常需要和微信、微校进行数据的交换,腾讯官方给出的方式使用Http方式,现在总结一下项目中通用的HttpUtils。HttpClient最基本的功能就是执行http方法,执行http方法包括了一...
  • 工具类代码: public static Response sendPostRequest(String url, Map&amp;lt;String, Object&amp;gt; params){ RestTemplate client = new RestTemplate(); HttpHeaders headers = new HttpHeaders()....
  • Java Https请求工具类

    2018-09-24 15:12:29
    由于微信API接口建议使用Https请求方式 而且过不久就废弃http请求方式了 所以提供以下Https工具类   public class SSLClient extends DefaultHttpClient{ public SSLClient() throws Exception{ super(); SSL...
  • 包括POST请求,GET请求。以及请求UTF-8编码。 代码如下: import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log;...import org.apache.commons.logging.LogFactory;...
  • public class R extends HashMap&lt;String, Object&gt; { private static final long serialVersionUID = 1L; public R() { put("code", 0); put("msg"... r...
  • java代码实现http请求工具类封装 参数介绍: get方式请求:url:请求地址的字符串 post方式请求:url:请求地址的字符串 jsonString:json字符串 注意:json字符串的生成的方法如下 需要封装的json格式如下:...
1 2 3 4 5 ... 20
收藏数 947,664
精华内容 379,065
关键字:

http工具类