我们知道目前有很多优秀的大名鼎鼎的http开源框架可以实现任何形式的http调用,在多年的开发经验中我都有使用过。比如apache的httpClient包,非常优秀的Okhttp,jersey client。
而Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率
引入如下依赖:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.7</version>
</dependency>
代码示例:
构造JSON参数:
JSONObject param = JSONUtil.createObj();
param.putOpt(column,value);
hutool工具的链式调用示例:
String result = HttpUtil.createPost(url)
.header(Header.CONTENT_TYPE, "application/json")
.header("appId", "xx")
.timeout(60000)
.body(param.toString()).execute().body();
对比下使用原始方式,以下是一个封装示例:
/**
* 发送json 请求
*
* @param url
* @param json
* @return
*/
public static String postWithJson(String url, String json) {
String returnValue = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("appId", "ZICXCRkUTBeNcP2eRfCnVQ");
httpPost.setEntity(requestEntity);
returnValue = httpClient.execute(httpPost, responseHandler);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnValue;
}
它非常好用,小巧快捷,类型特别全,简直开发神器。更多学习内容参考官网介绍:https://hutool.cn/
除此之外,另外一个优秀的 开源框架可以提供参考:https://gitee.com/dt_flys/forest 它能屏蔽不同细节http api所带来的所有差异,能通过简单的配置像调用rpc框架一样的去完成极为复杂的http调用。