OkHttpClientUtil

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)
            .build();

    /**
     * 发起 application/json 的 post 请求
     *
     * @param url           地址
     * @param param         参数
     * @param interfaceName 接口名称
     * @return
     * @throws Exception
     */
    public static  T postApplicationJson(String url, Object param, String interfaceName, Class clazz) {
        // 生成requestBody
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , JSON.toJSONString(param));

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

    /**
     * 发起 x-www-form-urlencoded 的 post 请求
     *
     * @param url           地址
     * @param param         参数
     * @param interfaceName 接口名称
     * @return
     * @throws Exception
     */
    public static  T postApplicationXWwwFormUrlencoded(String url, Object param, String interfaceName, Class clazz) {
        Map paramMap = JSON.parseObject(JSON.toJSONString(param), new TypeReference>() {
        });
        // 生成requestBody
        StringBuilder content = new StringBuilder(128);
        for (Map.Entry 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, clazz);
    }

    /**
     * 发起post请求,不做任何签名
     *
     * @param url           发送请求的URL
     * @param interfaceName 接口名称
     * @param requestBody   请求体
     * @param param         参数
     * @throws IOException
     */
    public static  T post(String url, String interfaceName, RequestBody requestBody, Object param, Class clazz) {
        Request request = new Request.Builder()
                //请求的url
                .url(url)
                .post(requestBody)
                .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("请求 {}  {},请求参数:{}, 返回参数:{}", interfaceName, url, JSON.toJSONString(param),
                    StringUtils.isEmpty(result) ? errorMsg : result);
        }

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

你可能感兴趣的:(OkHttpClientUtil)