后端CloseableHttpClient工具类
HttpClient是客户端的http通信实现库,这个类库的作用是接收和发送http报文,使用这个类库,它相比传统的 HttpURLConnection,增加了易用性和灵活性,我们对于http的操作会变得简单一些。
文章目录
前言
这篇文章将提供一个HttpClient的工具类,来访问http请求,得到响应数据。
一、应用场景
对接HTTP的接口,对方提供了接口,可以使用该工具类,获取接口的响应数据。
拿到数据后,再根据自己的需求,解析数据。
二、使用步骤
1.引入库
pom.xml中加入依赖
注意:
导入的是org.apache.httpcomponents包,不是commons-httpclient包。
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
1.1. fastjson说两句
fastjson有不同的包,这里用的是com.alibaba.fastjson。
1.1.1 net.sf.json和com.alibaba.fastjson对比
1、使用net.sf.json.JSONObject解析json精度丢失
测试的json数据:vector的值是double数组类型
{“vector”:[0.0,151.42662048339844,31.855236053466797,4.355315208435059,35.25135803222656,4.608330726623535],“success”:true}
使用net.sf.json.JSONObject,获取vector的数据:
JSONObject objData = new JSONObject().fromObject(jsonString);
Boolean suc = (Boolean)objData.get("success");
String vecStr = objData.get("feature_vector").toString();
// 获取到的vecStr值为:0,151.42662,31.855236,4.355315,35.251358,4.6083307。
// 精度由15位,截取到6~7位。
使用com.alibaba.fastjson.JSONObject,获取vector的数据:
Map obj= JSONObject.parseObject(jsonString, Map.class);
Boolean suc = (Boolean)obj.get("success");
String vecStr =obj.get("feature_vector").toString();
// 得到的vecStr的值为:
// [0.0,151.42662048339844,31.855236053466797,4.355315208435059,35.25135803222656,4.608330726623535]
2、使用net.sf.json.JSONArray.fromObject解析json字符串太慢
测试数据:
有几百个json文件,每个文件70M左右。
json文件的格式为:[{“str”: “xxx”, “num”: “2055”}, {“str”: “aaa”,“num”:“2542”},…]
使用 JSONArray.fromObject 获取:
Long start = System.currentTimeMillis();
JSONArray arrData = JSONArray.fromObject(json);
List<Map<String, String>> maps = JSONArray.toList(arrData, Map.class);
Long end = System.currentTimeMillis();
System.out.println(end-start);
// 执行以上程序解析json文件花费126820ms。
使用 com.alibaba.fastjson获取:
Long start = System.currentTimeMillis();
List<Map> maps = JSONObject.parseArray(json, Map.class);
Long end = System.currentTimeMillis();
System.out.println(end-start);
// 使用alibaba.fastjson执行程序解析json文件仅仅花费311ms
总结:解析json时还是使用alibaba.fastjson,比较靠谱。
1.1.1对比原文链接:https://blog.csdn.net/qq_23888451/article/details/89254879
1.1.2 net.sf.json和com.alibaba.fastjson获取对象方法区别
最后总结两者区别:
【1】json转换json对象
net.sf.json使用:
JSONObject object = JSONObject.fromObject(body);
com.alibaba.fastjson:
JSONObject object = JSONObject.parseObject(body);
【2】json对象转换成javabean对象
net.sf.json使用:
User user=(User) JSONObject.toBean(jsonObject, User.class);
com.alibaba.fastjson:
User user= JSON.parseObject(jsonObject.toJSONString(), User.class);
1.1.2 使用方法原文链接:https://www.codeleading.com/article/97761332817/
2.工具类
package com.wym.common.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* HttpClient工具类
*/
public class HttpClientUtils {
private static RequestConfig requestConfig = null;
static {
// 设置请求和传输超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
}
/**
* post请求传输json参数
*
* @param url url地址
* @param jsonParam 参数
* @return
*/
public static JSONObject httpPost(String url, JSONObject jsonParam) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
httpPost.setConfig(requestConfig);
try {
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = "";
try {
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* post请求传输String参数 例如:name=Jack&sex=1&type=2
* Content-type:application/x-www-form-urlencoded
*
* @param url url地址
* @param strParam 参数
* @return
*/
public static JSONObject httpPost(String url, String strParam) {
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
try {
if (null != strParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(strParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = "";
try {
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.releaseConnection();
}
return jsonResult;
}
/**
* post请求传输Map<String,String>参数 【没测试过,备用】
* Content-type:application/x-www-form-urlencoded
*
* @param url url地址
* @param params 参数
* @return
*/
public static String post(String url, Map<String,String> params){
HttpPost post = null;
CloseableHttpResponse response=null;
try{
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// // 设置超时时间
// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
// httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
List<NameValuePair> list = new ArrayList<NameValuePair>();
params.forEach((k,v) ->{
NameValuePair pair = new BasicNameValuePair(k, v);
list.add(pair);
});
UrlEncodedFormEntity entity=null;
entity = new UrlEncodedFormEntity(list,"UTF-8");
post = new HttpPost(url);
// 构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Close");
post.setEntity(entity);
response = httpClient.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity httpEntity = response.getEntity();
String result=EntityUtils.toString(httpEntity);
return result;
}else{
System.out.println("error");
}
}
catch (Exception e){
e.printStackTrace();
}finally {
if(post != null){
post.releaseConnection();
}
}
return "";
}
/**
* 发送get请求
*
* @param url 路径
* @return
*/
public static JSONObject httpGet(String url) {
// get请求返回结果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
HttpGet request = new HttpGet(url);
request.setConfig(requestConfig);
try {
CloseableHttpResponse response = client.execute(request);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(strResult);
} else {
}
} catch (IOException e) {
e.printStackTrace();
} finally {
request.releaseConnection();
}
return jsonResult;
}
}
3.调用post方法,传jsonArray对象
public void test(String[] args) {
String url = "http://ip:port/api/method";
JSONObject item = new JSONObject();
item.put("key1","value1");
item.put("key2","value2");
JSONArray array = new JSONArray();
array.add(item);
JSONObject result = HttpClientUtils.httpPost(url,array.toJSONString());
System.out.println(result);
}