HttpClient 模拟发送Post和Get请求 并用fastjson对返回json字符串数据解析,和HttpClient一些参数方法的deprecated(弃用)的综合总结

时间:2023-01-16 18:12:31
最近在做一个接口调用的时候用到Apache的httpclient时候,发现引入最新版本4.5,DefaultHttpClient等老版本常用的类已经过时了,不推荐使用了;去官网看了一下在4.3之后就抛弃了。

可以参考:

点击此处详情 推荐使用 CloseableHttpClient

HttpClient 模拟发送Post和Get请求 并用fastjson对返回json字符串数据解析,和HttpClient一些参数方法的deprecated(弃用)的综合总结

点击此处详情 设置过时参数等类也已经在4.3过后不推荐使用

HttpClient 模拟发送Post和Get请求 并用fastjson对返回json字符串数据解析,和HttpClient一些参数方法的deprecated(弃用)的综合总结

DefaultHttpClient --> CloseableHttpClient

HttpClient httpClient=new DefaultHttpClient(); --> CloseableHttpClient httpClient = HttpClients.createDefault();

HttpResponse --> CloseableHttpResponse
HttpResponse httpResponse = httpClient.execute(httpPost); --> CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

Post请求

/**
* Post方式 得到JSONObject
*
* @param paramsHashMap post参数
* @param url
* @param encoding 编码utf-8
* @return
*/
public JSONObject getJSONObjectByPost(Map<String, String> paramsHashMap, String url, String encoding) {
//创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault(); JSONObject result = null;
    //json方式
    //JSONObject jsonParam = new JSONObject();
    //jsonParam.put("name", "admin");
    //jsonParam.put("pass", "123456");
    //StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");
    //解决中文乱码问题
    //entity.setContentEncoding("UTF-8");
    //entity.setContentType("application/json");
    //httpPost.setEntity(entity);     //表单方式
List<NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>();
// 将传过来的参数添加到List<NameValuePair>中
if (paramsHashMap != null && !paramsHashMap.isEmpty()) {
//遍历map
for (Map.Entry<String, String> entry : paramsHashMap.entrySet()) {
nameValuePairArrayList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
     try {
// 利用List<NameValuePair>生成Post请求的实体数据
HttpPost httpPost = new HttpPost(url);
// 为HttpPost设置实体数据 UrlEncodedFormEntity 把输入数据编码成合适的内容
  httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairArrayList, encoding));
// HttpClient 发送Post请求
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// CloseableHttpResponse
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 10 * 1024);
StringBuilder strBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
strBuilder.append(line);
}
// 用fastjson的JSON将返回json字符串转为json对象
result = JSON.parseObject(strBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
//关闭流
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Get请求

public JSONObject getJSONObjectByGet(String url){
JSONObject resultJsonObject=null; //创建httpClient连接
CloseableHttpClient httpClient = HttpClients.createDefault(); StringBuilder urlStringBuilder=new StringBuilder(url);
StringBuilder entityStringBuilder=new StringBuilder();
//利用URL生成一个HttpGet请求
HttpGet httpGet=new HttpGet(urlStringBuilder.toString());
// HttpClient 发送Post请求
CloseableHttpResponse httpResponse = null;
try {
httpResponse=httpClient.execute(httpGet);
} catch (Exception e) {
e.printStackTrace();
}
//得到httpResponse的状态响应码
if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK) {
//得到httpResponse的实体数据
HttpEntity httpEntity=httpResponse.getEntity();
if (httpEntity!=null) {
BufferedReader reader=null;
try {
reader=new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);
String line=null;
while ((line=reader.readLine())!=null) {
entityStringBuilder.append(line);
}
// 从HttpEntity中得到的json String数据转为json
String json=entityStringBuilder.toString();
resultJsonObject=JSON.parseObject(json);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
//关闭流
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return resultJsonObject;
}
本文结合自己经历及收集网络知识综合个人总结,只为分享技术,方便解决问题,如有侵犯版权信息等,请联系我!