美文网首页
HttpClient使用

HttpClient使用

作者: knock | 来源:发表于2020-07-21 21:53 被阅读0次
    package kr.weitao.common.util;
    
    import com.alibaba.fastjson.JSONObject;
    import okhttp3.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.File;
    import java.util.*;
    import java.util.concurrent.TimeUnit;
    
    /**
     * @author yyd
     * 网络请求工具
     */
    public class HttpClientUtils {
    
        //client.newCall(request).enqueue(new Callback()  异步
        private static OkHttpClient client = null;
        private static HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
        private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    
        //编码
        public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    
        static {
            client = new OkHttpClient.Builder()
                    .cookieJar(new CookieJar() {
                        @Override
                        public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                            cookieStore.put(httpUrl.host(), list);
                        }
    
                        @Override
                        public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                            List<Cookie> cookies = cookieStore.get(httpUrl.host());
                            return cookies != null ? cookies : new ArrayList<Cookie>();
                        }
                    })
    //                .addInterceptor((chain)->{
    //                    int maxRetry=3;//最大重试次数
    //                    int retryNum = 0;//假如设置为3次重试的话,则最大可能请求4次(默认1次+3次重试)
    //
    //                    Request request = chain.request();
    //                    Response response = null;
    //                    try {
    //                        response = chain.proceed(request);
    //                    } catch (Exception e) {
    //                        e.printStackTrace();
    //                    }
    //                    while ((response == null || !response.isSuccessful()) && retryNum < maxRetry) {
    //                        retryNum++;
    //                        try {
    //                            response = chain.proceed(request);
    //                        } catch (Exception e) {
    //                            e.printStackTrace();
    //                        }
    //                    }
    //                    return response;
    //                })//连接失败 超时 请求失败 重试
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .connectionPool(connectionPool())
                    .build();
        }
    
        private static ConnectionPool connectionPool() {
            return new ConnectionPool(5, 5, TimeUnit.MINUTES);
        }
    
    
        /**
         * 同步 get请求
         *
         * @param url
         * @param head
         * @return
         */
        public static String executeGet(String url, Map<String, String> head) {
    
            String bodyStr = null;
            try {
                Request.Builder build = new Request.Builder().url(url);//请求接口。如果需要传参拼接到接口后面。
                if (head != null) {
                    Set<String> set = head.keySet();
                    for (String key : set) {
                        build.header(key, head.get(key));
                    }
                }
    
                Request request = build.build();//创建Request 对象
                Response response = null;
                response = client.newCall(request).execute();//得到Response 对象
    
                if (response.isSuccessful()) {
                    bodyStr = response.body().string();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
        /**
         * 同步 post请求
         *
         * @param url
         * @param head
         * @param param
         * @return
         */
        public static String executePost(String url, Map<String, String> head, Map<String, String> param) {
    
            String bodyStr = null;
            try {
    
                Request.Builder build = new Request.Builder().url(url);//创建Request 对象。
    
                if (head != null) {
                    Set<String> headSet = head.keySet();
                    for (String key : headSet) {
                        build.header(key, head.get(key));
                    }
                }
    
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
    
                if (param != null) {
                    Set<String> paramSet = param.keySet();
                    for (String key : paramSet) {
                        formBody.add(key, param.get(key));//传递键值对参数
                    }
                }
    
                Request request = build.post(formBody.build()).build();//传递请求体
    
                Response response = null;
                response = client.newCall(request).execute();//得到Response 对象
                if (response.isSuccessful()) {
                    bodyStr = response.body().string();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
        /**
         * 同步 文件上传
         *
         * @param url
         * @param head
         * @param files
         * @param param
         * @return
         */
        public static String executeUploadFileAndParam(String url, Map<String, String> head, List<File> files, Map<String, String> param) {
            String bodyStr = null;
            try {
    
                Request.Builder build = new Request.Builder().url(url);
    
                if (head != null) {
                    Set<String> headSet = head.keySet();
                    for (String key : headSet) {
                        build.header(key, head.get(key));
                    }
                }
    
    
                MultipartBody.Builder multiBuild = new MultipartBody.Builder();
                //设置类型
                multiBuild.setType(MultipartBody.FORM);
    
                if (files != null) {
                    for (int i = 0; i < files.size(); i++) {
                        multiBuild.addFormDataPart("file", files.get(i).getName(), RequestBody.create(null, files.get(i)));
                    }
                }
    
                if (param != null) {
                    Set<String> paramSet = param.keySet();
                    for (String key : paramSet) {
                        multiBuild.addFormDataPart(key, param.get(key));//传递键值对参数
                    }
    
                }
    
                //创建Request 对象。
                Request request = build.post(multiBuild.build()).build();//传递请求体
    
                Response response = null;
                response = client.newCall(request).execute();//得到Response 对象
                if (response.isSuccessful()) {
                    bodyStr = response.body().string();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
        public static String executePost(String url, String json, Map<String, String> head) {
            String bodyStr = null;
            try {
                Request.Builder build = new Request.Builder().url(url);
    
                if (head != null) {
                    Set<String> headSet = head.keySet();
                    for (String key : headSet) {
                        build.header(key, head.get(key));
                    }
                }
    
                RequestBody body = RequestBody.create(JSON, json);
                Request request = build.post(body).build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    bodyStr = response.body().string();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
        public static byte[] executeGetToBytes(String url, Map<String, String> head) {
    
            byte[] bodyStr = new byte[0];
            try {
                Request.Builder build = new Request.Builder().url(url);//请求接口。如果需要传参拼接到接口后面。
                if (head != null) {
                    Set<String> set = head.keySet();
                    for (String key : set) {
                        build.header(key, head.get(key));
                    }
                }
    
                Request request = build.build();//创建Request 对象
                Response response = null;
                response = client.newCall(request).execute();//得到Response 对象
    
                if (response.isSuccessful()) {
                    bodyStr = response.body().bytes();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
        public static byte[] executePostToBytes(String url, String json, Map<String, String> head) {
            byte[] bodyStr = new byte[0];
            try {
                Request.Builder build = new Request.Builder().url(url);
    
                if (head != null) {
                    Set<String> headSet = head.keySet();
                    for (String key : headSet) {
                        build.header(key, head.get(key));
                    }
                }
    
                RequestBody body = RequestBody.create(JSON, json);
                Request request = build.post(body).build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    bodyStr = response.body().bytes();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
        public static String executeDelete(String url, String json, Map<String, String> head) {
            String bodyStr = null;
            try {
    
                Request.Builder build = new Request.Builder().url(url);
    
                if (head != null) {
                    Set<String> headSet = head.keySet();
                    for (String key : headSet) {
                        build.header(key, head.get(key));
                    }
                }
    
                RequestBody body = RequestBody.create(JSON, json);
                Request request = build.delete(body).build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    bodyStr = response.body().string();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
        public static String executePut(String url, String json, Map<String, String> head) {
            String bodyStr = null;
            try {
                Request.Builder build = new Request.Builder().url(url);
    
                if (head != null) {
                    Set<String> headSet = head.keySet();
                    for (String key : headSet) {
                        build.header(key, head.get(key));
                    }
                }
    
                RequestBody body = RequestBody.create(JSON, json);
                Request request = build.put(body).build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    bodyStr = response.body().string();
                } else {
                    logger.warn("bodyStr:{}" ,response.body().string());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bodyStr;
        }
    
    
      public static void main(String[] args) throws Exception {
    
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                    .setNameFormat("demo-pool-%d").build();
            ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    
            singleThreadPool.execute(()-> System.out.println(Thread.currentThread().getName()));
            singleThreadPool.shutdown();
    
        }
    
    }
    
    
    

    pom.xml

    
            <!-- okhttp -->
            <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.13.1</version>
            </dependency>
    
    

    相关文章

      网友评论

          本文标题:HttpClient使用

          本文链接:https://www.haomeiwen.com/subject/moxgkktx.html