• http请求方式OkHttpClient


    http请求方式-OkHttpClient

    import com.example.core.mydemo.http.OrderReqVO;
    import okhttp3.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.CollectionUtils;
    
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    
    public class OkHttpClient {
        private static Logger log = LoggerFactory.getLogger(OkHttpClient.class);
    
        private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
        private volatile static okhttp3.OkHttpClient client;
    
        private static final int MAX_IDLE_CONNECTION = 2;
        private static final long KEEP_ALIVE_DURATION = 2;
        private static final long CONNECT_TIMEOUT = 1000;
        private static final long READ_TIMEOUT = 3000;
    
        /**
         * 单例模式(双重检查模式) 获取类实例
         *
         * @return client
         */
        private static okhttp3.OkHttpClient getInstance() {
            if (client == null) {
                synchronized (okhttp3.OkHttpClient.class) {
                    if (client == null) {
                        client = new okhttp3.OkHttpClient.Builder()
                                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                                .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,
                                        TimeUnit.MINUTES))
                                .build();
                    }
                }
            }
            return client;
        }
    
        public static String syncPost(String url, String json) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            try {
                Response response = OkHttpClient.getInstance().newCall(request).execute();
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    log.info("syncPost response = {}, responseBody= {}", response, result);
                    return result;
                }
                String result = response.body().string();
                log.info("syncPost response = {}, responseBody= {}", response, result);
                throw new IOException("三方接口返回http状态码为" + response.code());
            } catch (Exception e) {
                log.error("syncPost() url:{} have a ecxeption {}", url, e);
                throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
            }
        }
    
        public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {
            Request request;
            final Request.Builder builder = new Request.Builder().url(url);
            try {
                if (!CollectionUtils.isEmpty(headParamsMap)) {
                    final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
                            .iterator();
                    while (iterator.hasNext()) {
                        final Map.Entry<String, Object> entry = iterator.next();
                        builder.addHeader(entry.getKey(), (String) entry.getValue());
                    }
                }
                request = builder.build();
                Response response = OkHttpClient.getInstance().newCall(request).execute();
                String result = response.body().string();
                log.info("syncGet response = {},responseBody= {}", response, result);
                if (!response.isSuccessful()) {
                    throw new IOException("三方接口返回http状态码为" + response.code());
                }
                return result;
            } catch (Exception e) {
                log.error("remote interface url:{} have a ecxeption {}", url, e);
                throw new RuntimeException("三方接口返回异常");
            }
        }
    
        public static void main(String[] args) {
            OrderReqVO data = new OrderReqVO();
            data.setOrderNum("111123333");
            data.setServerType("1");
    
    
            String url = "https://域名/接口名称";
    
            try {
                String resp = syncPost(url, com.alibaba.fastjson.JSON.toJSONString(data));
                System.out.println("resp = " + resp);
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
    }
  • 相关阅读:
    PLC 控制系统资源
    .net core 控制台程序生成EXE
    EF Core 日志跟踪sql语句
    Oracle 设置自启动
    数据库批量插入数据
    字符串面试题系列之六:在字符串中删除特定的字符
    字符串面试题系列之五:删除字符串空格
    字符串面试题系列之四:字符串匹配二
    字符串面试题系列之三:左旋转字符串
    字符串面试题系列之二:连续最长数字串
  • 原文地址:https://www.cnblogs.com/oktokeep/p/16789349.html
Copyright © 2020-2023  润新知