HttpClient 模拟发送Post和Get请求 并用fastjson对返回json字符串数据解析,和HttpClient一些参数方法的deprecated(弃用)的综合总结
最近在做一个接口调用的时候用到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(弃用)的综合总结的更多相关文章
- Jsoup请求http或https返回json字符串工具类
Jsoup请求http或https返回json字符串工具类 所需要的jar包如下: jsoup-1.8.1.jar 依赖jar包如下: httpclient-4.5.4.jar; httpclient ...
- springboot+shiro 02 - 异步ajax请求无权限时,返回json格式数据
博客: https://www.cnblogs.com/youxiu326/p/shiro-01.html github:https://github.com/youxiu326/sb_shiro_s ...
- php模拟发送GET和POST请求
php分别模拟发送GET和POST请求,非常实用的额,也可作PHP CURL入门级的理解教材的,示例代码如下: <?php /* ** php分别模拟发送GET与POST请求 ** */ fun ...
- 使用jQuery发送POST,Ajax请求返回JSON格式数据
问题: 使用jQuery POST提交数据到PHP文件, PHP返回的json_encode后的数组数据,但jQuery接收到的数据不能解析为JSON对象,而是字符串{"code" ...
- ajax请求返回json字符串/json对象 处理
1. 返回json字符串如何处理 $.ajax({ url:xxx, success:function(date){ }, error:function(){ } }); 通过最原始的返回: Prin ...
- 请求*.html后缀无法返回json数据的问题
在springmvc中请求*.html不可以返回json数据. 修改web.xml,添加url拦截格式.
- 根据传入url请求,返回json字符串
/** * 根据传入url请求,返回json字符串 * @param url * @return * @throws UnsupportedEncodingException */ public st ...
- ajax请求后台,返回json格式数据,模板!
添加一个用户的时候,需要找出公司下所有的部门,和相应部门下的角色,利用ajax请求,实现联动技术.将返回的json格式数据,添加到select标签下. <script type="te ...
- springmvc通过ajax异步请求返回json格式数据
jsp 首先创建index.jsp页面 <script type="text/javascript"> $(function () { $("#usernam ...
随机推荐
- GET请求/百度贴吧 有bug
# -*- coding:utf-8 -*- import urllib, urllib2 import re import sys class Cuzz(): """这 ...
- cs231n --- 1:线性svm与softmax
cs231n:线性svm与softmax 参数信息: 权重 W:(D,C) 训练集 X:(N,D),标签 y:(N,1) 偏置量bias b:(C,1) N:训练样本数: D:样本Xi 的特征维度, ...
- java String,StringBuffer和StringBulder学习笔记
1.String:不可改变的Unicode字符序列. 池化思想,把需要共享的数据放在池中,用一个存储区域来存放一些公用资源以减少存储空间的开销. 在String类中,以字面值创建时,回到java方法空 ...
- 工作随笔——selenium支持post请求,支持自定义header
背景: 最近在写一个小程序,发现博主所在的地区访问该网站时有防ddos功能验证导致程序不能正常工作. 经过试验发现可以用国外代理ip解决这个问题,但是程序走代理访问延迟高且不稳定. 思路: selen ...
- 微信小程序教学第三章第三节(含视频):小程序中级实战教程:视图与数据关联
§ 视图与数据关联 本文配套视频地址: https://v.qq.com/x/page/z0554wyswib.html 开始前请把 ch3-3 分支中的 code/ 目录导入微信开发工具 首先 首先 ...
- JavaScript基础3——关于运算符
算数运算符 算数运算符有+.-.*./.%.++.--.=.类似+=的运算符,其使用方式与编程语言(Java.C++.C#等)基本一样.给定 y=5,下面的表格解释了这些算术运算符: 运算符 描述 例 ...
- Hive实际应用小结
1.简介 Hive是数据仓库平台,构建在Hadoop之上用来处理结构化数据.Hive是一个SQL解析引擎,能够将SQL语句转化成MapReduce作业并在Hadoop上执行,从而使得查询和分析更加方便 ...
- [数据结构]C语言队列的实现
我个人把链表.队列.栈分为一类,然后图.树分为一类.(串不考虑),分类的理由就是每一类有规律可循,即你能通过修改极少数的代码把链表变成队列.栈.(这里我们不考虑其他诸如设计模式等因素),因此本贴在讲完 ...
- Docker(三):Docker仓库配置
1.仓库介绍 仓库(repository)用来集中管理Docker镜像,支持镜像分发和更新. 目前世界上最大最知名的公共仓库是Docker官方的Docker Hub,国内比较知名的有:Docker P ...
- day 10 字符编码和文件处理 细节整理
pycharm是文本编辑器. 大概理解为: 输出到屏幕上的时候,是解码过的字符串,用 decode 处理的时候要编码成相应的流, encode 成你要用的格式就可以了 1 .字符编码: 字符==== ...