什么是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)
.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);
}
}
关于什么是OkHttpClientUtil问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/xiaolyuh/blog/3121774