最近在做一个接口调用的时候用到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. HTML: width,height

    在进行前端页面开发时,width(width,offsetWidth,scrollWidth,clientWidth)height(height,offsetHeight,scrollHeight,c ...

  2. 在IDEA中实战Git(转载自)

    转载自:http://blog.csdn.net/autfish/article/details/52513465 工作中多人使用版本控制软件协作开发,常见的应用场景归纳如下: 假设小组中有两个人,组 ...

  3. 4.python迭代器生成器装饰器

    容器(container) 容器是一种把多个元素组织在一起的数据结构,容器中的元素可以逐个地迭代获取,可以用in, not in关键字判断元素是否包含在容器中.通常这类数据结构把所有的元素存储在内存中 ...

  4. Hibernate缓存和状态

    缓存是介于应用程序和物理数据源之间,其作用是为了降低应用程序对物理数据源访问的频次,从而提高了应用的运行性能.   缓存的介质一般是内存,所以读写速度很快.但如果缓存中存放的数据量非常大时,也会用硬盘 ...

  5. vi 和vim 的区别

    它们都是多模式编辑器,不同的是vim 是vi的升级版本,它不仅兼容vi的所有指令,而且还有一些新的特性在里面.vim的这些优势主要体现在以下几个方面:1.多级撤消我们知道在vi里,按 u只能撤消上次命 ...

  6. python自动生成excel报表

    1.将SQL语句查询的内容,直接写入到excel报表中,以下为全部脚本.要求:此版本必须运维在windows平台,并且安装了excel程序,excel版本不限. python版本为2.7 if b 判 ...

  7. 豹哥嵌入式讲堂:ARM开发中有用的文件(1)- source文件

    大家好,我是豹哥,猎豹的豹,犀利哥的哥.今天豹哥给大家讲的是嵌入式开发里的source文件种类. 众所周知,嵌入式开发属于偏底层的开发,主要编程语言是C和汇编.所以本文要讲的source文件主要指的就 ...

  8. Web API系列之三 基本功能实现

    Web API系列之二讲解了如何搭建一个WebApi的基架,本文主要在其基础之上实现基本的功能.下面开始逐步操作: 一.配置WebApi的路由-用于配置外部如何访问内部资源的url的规则 1.添加Gl ...

  9. oracle12c_安装3——部署

    数据库安装后需要根据实际情况修改相关参数. 1.生成pfile以防万一. SQL> create pfile from spfile; 2.修改内存参数 只要设置MEMORY_MAX_TARGE ...

  10. Oracle12c_安装1——准备工作

    1.建议用户和组 su root #切换到root groupadd oinstall #创建用户组oinstall groupadd dba #创建用户组dba useradd -g oinstal ...