天天看點

OkHttp 工具類

/**
 * OkHttpClient工具
 *
 * @author yuhao.wang3
 */
public abstract class OkHttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpClientUtil.class);

    private static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getTrustManager())
            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
            .build();

    /**
     * 發起 application/json 的 post 請求
     *
     * @param url           位址
     * @param param         參數
     * @param interfaceName 接口名稱
     * @return
     * @throws Exception
     */
    public static <T> T postApplicationJson(String url, Object param, String interfaceName, Class<T> clazz) {
        // 生成requestBody
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , JSON.toJSONString(param));

        return post(url, interfaceName, requestBody, param, null, clazz);
    }

    /**
     * 發起 application/json 的 post 請求
     *
     * @param url           位址
     * @param param         參數
     * @param interfaceName 接口名稱
     * @return
     * @throws Exception
     */
    public static <T> T postApplicationJson(String url, Object param, Map<String, String> header, String interfaceName, Class<T> clazz) {
        // 生成requestBody
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , JSON.toJSONString(param));

        return post(url, interfaceName, requestBody, param, header, clazz);
    }

    /**
     * 發起 x-www-form-urlencoded 的 post 請求
     *
     * @param url           位址
     * @param param         參數
     * @param interfaceName 接口名稱
     * @return
     * @throws Exception
     */
    public static <T> T postApplicationXWwwFormUrlencoded(String url, Object param, String interfaceName, Class<T> clazz) {
        Map<String, String> paramMap = JSON.parseObject(JSON.toJSONString(param), new TypeReference<Map<String, String>>() {
        });
        // 生成requestBody
        StringBuilder content = new StringBuilder(128);
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            content.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if (content.length() > 0) {
            content.deleteCharAt(content.length() - 1);
        }

        RequestBody requestBody = FormBody.create(MediaType.parse("application/x-www-form-urlencoded"), content.toString());

        return post(url, interfaceName, requestBody, param, null, clazz);
    }

    /**
     * 發起post請求,不做任何簽名
     *
     * @param url           發送請求的URL
     * @param interfaceName 接口名稱
     * @param requestBody   請求體
     * @param param         參數
     */
    public static <T> T post(String url, String interfaceName, RequestBody requestBody, Object param, Map<String, String> headers, Class<T> clazz) {
        Request.Builder builder = new Request.Builder()
                //請求的url
                .url(url)
                .post(requestBody);

        if (MapUtils.isNotEmpty(headers)) {
            for (String key : headers.keySet()) {
                builder.addHeader(key, headers.get(key));
            }
        }
        Request request = builder.build();

        Response response = null;
        String result = "";
        String errorMsg = "";
        try {
            //建立/Call
            response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                logger.error("通路外部系統異常 {}: {}", url, response.toString());
                errorMsg = String.format("通路外部系統異常:%s", response.toString());
                throw new RemoteAccessException(errorMsg);
            }
            result = response.body().string();
        } catch (RemoteAccessException e) {
            logger.warn(e.getMessage(), e);
            result = e.getMessage();
            throw e;
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
            if (Objects.isNull(response)) {
                errorMsg = String.format("通路外部系統異常::%s", e.getMessage());
                throw new RemoteAccessException(errorMsg, e);
            }
            errorMsg = String.format("通路外部系統異常:::%s", response.toString());
            throw new RemoteAccessException(errorMsg, e);
        } finally {
            logger.info("請求 {}  {},請求參數:{}, header:{}, 傳回參數:{}", interfaceName, url, JSON.toJSONString(param),
                    JSON.toJSONString(headers), StringUtils.isEmpty(result) ? errorMsg : result);
        }

        return JSON.parseObject(result, clazz);
    }
}