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 ...
随机推荐
- java与数据库
工具:mysql: java eclipse,phpstudy. 以MySQL为例 java连接MySQL可能你在度娘的帮助下,又设置环境变量又改这改那的,结果还是没有连接成功. 今天我来分享一下不需 ...
- 【JMeter】选项-函数助手对话框应用举例
String date="${__javaScript((new Date()).getFullYear()+'-'+((new Date()).getMonth()+1)+'-'+(new ...
- MongoDB入门系列(二):Insert、Update、Delete、Drop
概述 本章节介绍Insert.Update.Delete.Drop操作基本语法. 环境: Version:3.4 insert insert()基本语法如下: db.collection.insert ...
- 【model模型传入view的数据类型错误】传入字典的模型项的类型为“System.Data.Entity.Infrastructure.DbQuery`1[MapScience.PovertyAlleviation.Web.Models.Qu
出现这个问题的原因是控制器中传给view的数据类型与View中设置的model类型不一致导致,比如控制器返回的IList类型的,而你在View里面model设置的是IEnumerable<> ...
- JavaWeb之数据源连接池(2)---C3P0
我们接着<JavaWeb之数据源连接池(1)---DBCP>继续介绍数据源连接池. 首先,在Web项目的WebContent--->WEB-INF--->lib文件夹中添加C3 ...
- Find Unique pair in an array with pairs of numbers 在具有数字对的数组中查找唯一对
给定一个数组,其中每个元素出现两次,除了一对(两个元素).找到这个唯一对的元素. 输入:第一行输入包含一个表示测试用例数的整数T.然后T测试用例如下.每个测试用例由两行组成.每个测试用例的第一行包含整 ...
- bzoj 3597: [Scoi2014]方伯伯运椰子
Description Input 第一行包含二个整数N,M 接下来M行代表M条边,表示这个交通网络 每行六个整数,表示Ui,Vi,Ai,Bi,Ci,Di 接下来一行包含一条边,表示连接起点的边 Ou ...
- React Native出现"Native module cannot be null"问题
经查跟PushNotification有关,需要手动完成Linking. 两步解决此问题: 配置Linking Libraries:https://facebook.github.io/react-n ...
- Macaca环境搭建踩坑总结
1.使用命令 npm i macaca-android -g 安装一直不成功,使用Macaca doctor 一直没有显示出android C:\Users\ABC>npm i macaca- ...
- Webpack 2 视频教程 012 - 理解Webpack 中的 CSS 作用域与 CSS Modules
原文发表于我的技术博客 这是我免费发布的高质量超清「Webpack 2 视频教程」. Webpack 作为目前前端开发必备的框架,Webpack 发布了 2.0 版本,此视频就是基于 2.0 的版本讲 ...