使用Apache HttpClient 4.x发送Json数据

时间:2022-06-16 04:42:13

Apache HttpClient是Apache提供的一个开源组件,使用HttpClient可以很方便地进行Http请求的调用。自4.1版本开始,HttpClient的API发生了较大的改变,很多方法的调用方式已经和3.x版本不同。本文使用的是当前最新的4.5.3版本。

首先在pom文件中引入httpcomponents依赖包:

 <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>

本文展示的是POST请求。

 import java.io.IOException;

 import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; /**
* @author
*
* @date 2017年5月18日 上午9:17:30
*
* @Description
*/
public class HttpPostUtils {
/**
*
* @param uri
* the request address
* @param json
* the request data that must be a JSON string
* @param connectTimeout
* the timeout in milliseconds until a connection is established
* @param connectionRequestTimeout
* the timeout in milliseconds used when requesting a connection
* from the connection manager
* @param socketTimeout
* the socket timeout in milliseconds, which is the timeout for
* waiting for data or, put differently, a maximum period
* inactivity between two consecutive data packets
* @return null when method parameter is null, "", " "
* @throws IOException
* if HTTP connection can not opened or closed successfully
* @throws ParseException
* if response data can not be parsed successfully
*/
public String postJson(String uri, String json, int connectTimeout, int connectionRequestTimeout, int socketTimeout)
throws IOException, ParseException {
if (StringUtils.isAnyBlank(uri, json)) {
return null;
} CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(uri);
// Create request data
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
// Set request body
post.setEntity(entity); RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout).setSocketTimeout(socketTimeout).build();
post.setConfig(config);
// Response content
String responseContent = null;
CloseableHttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
responseContent = EntityUtils.toString(response.getEntity(), Consts.UTF_8.name());
}
} finally {
if (ObjectUtils.anyNotNull(response)) {
response.close();
}
if (ObjectUtils.anyNotNull(client)) {
client.close();
}
}
return responseContent;
}
}

使用Apache HttpClient 4.x发送Json数据的更多相关文章

  1. HttpClient发送Json数据到指定接口

    项目中遇到将Json数据发送到指定接口,于是结合网上利用HttpClient进行发送. /** * post发送json数据 * @param url * @param param * @return ...

  2. SpringMVC客户端发送json数据时报400错误

    当测试客户端发送json数据给服务器时,找不到响应路径? 原来是参数类型不符,即使是json也要考虑参数的个数和类型 解决:将age请求参数由"udf"改为"3&quot ...

  3. iOS开发网络篇—发送json数据给服务器以及多值参数

    iOS开发网络篇—发送json数据给服务器以及多值参数 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 (2)设置请求头 (3)设置JSON数据为请求体 ...

  4. 【转】iOS开发网络篇—发送json数据给服务器以及多值参数

    原文: http://www.cnblogs.com/wendingding/p/3950132.html 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 ...

  5. perl post发送json数据

    sub  wx_init {                #$login_url ="https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=- ...

  6. JSON的简单使用&lowbar;向前台发送JSON数据

    转自:http://www.cnblogs.com/digdeep/p/5574366.html 1.前台页面 <%@ page language="java" conten ...

  7. python 全栈开发,Day75&lpar;Django与Ajax&comma;文件上传&comma;ajax发送json数据&comma;基于Ajax的文件上传&comma;SweetAlert插件&rpar;

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

  8. IOS-网络&lpar;发送JSON数据给服务器和多值参数)

    三步走: 1.使用POST请求 2.设置请求头 [request setValue:@"application/json" forHTTPHeaderField:@"Co ...

  9. ajax使用向Spring MVC发送JSON数据出现 org&period;springframework&period;web&period;HttpMediaTypeNotSupportedException&colon; Content type &&num;39&semi;application&sol;x-www-form-urlencoded&semi;charset&equals;UTF-8&&num;39&semi; not supported错误

    ajax使用向Spring MVC发送JSON数据时,后端Controller在接受JSON数据时报org.springframework.web.HttpMediaTypeNotSupportedE ...

随机推荐

  1. About vector

    今天打vector又打炸了不!高!兴! vecotr头文件 #include<vector> 定义域 using namespace std; 或using std::vector; 初始 ...

  2. shell学习之路&colon;重定向符号的使用

    http://note.youdao.com/share/?id=096963bf2a0862fd338919d781636be2&type=note 快捷键:   ​  

  3. hdu3033 分组背包

    //Accepted 896 KB 156 ms //http://blog.csdn.net/juststeps/article/details/8712150 //dp[i][l]=max(dp[ ...

  4. ES6 中的 Set、Map 和 WeakMap

    Set 是 ES6 新增的有序列表集合,它不会包含重复项. Set 支持 add(item) 方法,用来向 Set 添加任意类型的元素,如果已经添加过则自动忽略: has(item) 方法用来检测 S ...

  5. 【算法与数据结构】在n个数中取第k大的数(基础篇)

    (转载请注明出处:http://blog.csdn.net/buptgshengod) 题目介绍            在n个数中取第k大的数(基础篇),之所以叫基础篇是因为还有很多更高级的算法,这些 ...

  6. 【转】 Linux中的工作队列

    原文网址:http://blog.chinaunix.net/uid-20583479-id-1920134.html 工作队列一般用来做滞后的工作,比如在中断里面要做很多事,但是比较耗时,这时就可以 ...

  7. unix c 01

    gcc编译器(代码的 预处理/汇编/编译/连接) C程序员一般写程序会定义 .c和.h两种文件 .c文件(源文件)中一般放代码的实现,.h文件(头文件)中放 各种声明和定义.   gcc -E __. ...

  8. iOS 之 UINavigationController 记录

    有一阵子没有写随笔,感觉有点儿手生.一个多月以后终于又一次坐下来静下心写随笔,记录自己的学习笔记,也希望能够帮到大家. 废话少说回到正题,UINavigationController是IOS编程中比较 ...

  9. 2014 I&sol;O返回:Google连接一切

    文/蒋涛 6月.WWDC 2014与Google I/O  (大部分演讲视频都公开.Youtube须要FQ.很值得一看)相继召开. 今年是我第三年參加Google I/O大会.三年间,Google积累 ...

  10. 一键启动frida server的cmd脚本

    和以前写过的在pc直接操作的手机端的sqlite的脚本类似,需要用到重定向的命令 frida-server_helper.bat su /data/local/tmp/frida-server fri ...