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

可以参考:

点击此处详情 推荐使用 CloseableHttpClient

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

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;
}
本文结合自己经历及收集网络知识综合个人总结,只为分享技术,方便解决问题,如有侵犯版权信息等,请联系我!

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

  1. Jsoup请求http或https返回json字符串工具类

    Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...

  2. springboot+shiro 02 - 异步ajax请求无权限时,返回json格式数据

    博客: https://www.cnblogs.com/youxiu326/p/shiro-01.html github:https://github.com/youxiu326/sb_shiro_s ...

  3. php模拟发送GET和POST请求

    php分别模拟发送GET和POST请求,非常实用的额,也可作PHP CURL入门级的理解教材的,示例代码如下: <?php /* ** php分别模拟发送GET与POST请求 ** */ fun ...

  4. 使用jQuery发送POST,Ajax请求返回JSON格式数据

    问题: 使用jQuery POST提交数据到PHP文件, PHP返回的json_encode后的数组数据,但jQuery接收到的数据不能解析为JSON对象,而是字符串{"code" ...

  5. ajax请求返回json字符串/json对象 处理

    1. 返回json字符串如何处理 $.ajax({ url:xxx, success:function(date){ }, error:function(){ } }); 通过最原始的返回: Prin ...

  6. 请求*.html后缀无法返回json数据的问题

    在springmvc中请求*.html不可以返回json数据. 修改web.xml,添加url拦截格式.

  7. 根据传入url请求,返回json字符串

    /** * 根据传入url请求,返回json字符串 * @param url * @return * @throws UnsupportedEncodingException */ public st ...

  8. ajax请求后台,返回json格式数据,模板!

    添加一个用户的时候,需要找出公司下所有的部门,和相应部门下的角色,利用ajax请求,实现联动技术.将返回的json格式数据,添加到select标签下. <script type="te ...

  9. springmvc通过ajax异步请求返回json格式数据

    jsp 首先创建index.jsp页面 <script type="text/javascript"> $(function () { $("#usernam ...

随机推荐

  1. css盒子模型(3)

    盒子模型 版权声明 本文原创作者:雨点的名字 作者博客地址:https://home.cnblogs.com/u/qdhxhz/      在讲理论之前,我们先要知道网页设计中常听的属性名:内容(co ...

  2. 微信小程序教学第四章第一节(含视频):小程序中级实战教程:详情-页面制作

    详情 - 页面制作 本文配套视频地址: https://v.qq.com/x/page/o0555o20xjd.html 开始前请把 ch4-1 分支中的 code/ 目录导入微信开发工具 这一章节中 ...

  3. 【python】入门:打印字符串、简单计算

  4. JDBC开源框架:DBUtils使用入门

    在单元测试过程中,只涉及到数据库的直接操作来验证业务逻辑是否正确的情况,DBUtils非常适合使用.它结构简单,包小,友好处理掉那些jdbc异常,让你更专注于业务代码,而非底层的操作.官网对它的定义: ...

  5. ES6之Set方法与Map方法

    ES6提供了新的数据结构--Set与Map,Set本身是一个构造函数且成员的值是唯一的,没有重复的值!!!Set()是一个存储已排序的无重复元素的数据而Map()是一对数据Map()使用关键值Key来 ...

  6. 浅谈,html\css脱离标准文档流相关

    (个人知识有限,难免有误,请见谅) 标准文档流,顾名思义,是要按照一定规矩排列的,默认的就是元素会从左至右,从上至下排列,块级会独占一行,行内元素会和小伙伴们共享一行. 本来在标准文档流下,各个元素相 ...

  7. Simple Games Using SpriteKit

    p.p1 { margin: 0.0px 0.0px 12.0px 0.0px; line-height: 14.0px; font: 12.0px Times; color: #000000 } s ...

  8. KD树小结

    很久之前我就想过怎么快速在二维平面上查找一个区域的信息,思考许久无果,只能想到几种优秀一点的暴力. Kd树就是干上面那件事的. 别的不多说,赶紧把自己的理解写下来,免得凉了. KD树的组成 以维护k维 ...

  9. bat常用命令

    1.@它的作用是隐藏它后面这一行的命令本身(只能影响当前行).2.echo中文为"反馈"."回显"的意思.它其实是一个开关命令,就是说它只有两种状态:打开和关闭 ...

  10. Git知识总览(一) 从 git clone 和 git status 谈起

    本篇博客是整理git相关知识的第一篇,因为之前一直是用SourceTree对Git的命令行操作用的不是特别熟,于是乎过了一遍ProGit(链接:https://git-scm.com/book/zh/ ...