使用Apache HttpClient 4.x发送Json数据
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数据的更多相关文章
- HttpClient发送Json数据到指定接口
项目中遇到将Json数据发送到指定接口,于是结合网上利用HttpClient进行发送. /** * post发送json数据 * @param url * @param param * @return ...
- SpringMVC客户端发送json数据时报400错误
当测试客户端发送json数据给服务器时,找不到响应路径? 原来是参数类型不符,即使是json也要考虑参数的个数和类型 解决:将age请求参数由"udf"改为"3" ...
- iOS开发网络篇—发送json数据给服务器以及多值参数
iOS开发网络篇—发送json数据给服务器以及多值参数 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 (2)设置请求头 (3)设置JSON数据为请求体 ...
- 【转】iOS开发网络篇—发送json数据给服务器以及多值参数
原文: http://www.cnblogs.com/wendingding/p/3950132.html 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 ...
- perl post发送json数据
sub wx_init { #$login_url ="https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=- ...
- JSON的简单使用_向前台发送JSON数据
转自:http://www.cnblogs.com/digdeep/p/5574366.html 1.前台页面 <%@ page language="java" conten ...
- python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)
昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...
- IOS-网络(发送JSON数据给服务器和多值参数)
三步走: 1.使用POST请求 2.设置请求头 [request setValue:@"application/json" forHTTPHeaderField:@"Co ...
- ajax使用向Spring MVC发送JSON数据出现 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported错误
ajax使用向Spring MVC发送JSON数据时,后端Controller在接受JSON数据时报org.springframework.web.HttpMediaTypeNotSupportedE ...
随机推荐
- [翻译]Review——How JavaScript works:The building blocks of Web Workers
原文地址:https://blog.sessionstack.com/how-javascript-works-the-building-blocks-of-web-workers-5-cases-w ...
- 浅谈ul布局以及table布局
我个人对于某些言论说要注重html语义化在布局中的应用,我反而不怎么感冒,试试兼容IE7&&项目期相对较赶的情况下,我还是推荐快速开发为主,兼容性强为主. 如果布局中需要用户边框,推荐 ...
- bootstrap框架怎么在html页面加载使用
今天敲代码的时候,正好碰到这个问题. 与大家分享这个解决方法: 1/7 到bootstrap官方网站下载,对于我们开发者来说,直接下载编译和压缩后的CSS.JavaScript文件,另外还包含 ...
- CSS3字体火焰燃烧效果
动画的CSS: // fire @keyframes fireDiv { 0% { text-shadow: 0 0 4px white, 0 -5px 4px #ff3, 2px -10px 6px ...
- drupal7 自定义登录&找回密码页面,注意事项
1.登录页面的 $form['form_id'] 和 $form['form_build_id'],是这样输出的: <?php print drupal_render($form['form_i ...
- WDCP服务器升级之后伪静态缓存文件.htaccess读取失效
当购买或者升级服务器之后,thinkphp3框架的默认缓存文件.htaccess读取失效,解决方法如下: 1.我的网站是thinkphp3 服务器环境是N+A模式 2.将网站根目录的.htaccess ...
- Linux / mysql: is it safe to copy mysql db files with cp command from one db to another?
Copying is very simple for MyISAM and completely 100% risky (near suicidal) with InnoDB. From your q ...
- SQL Server ->> 性能调优案例之 -- 包含递归查询的视图导致整个查询语句性能下降
有个语句最近性能下降很厉害,原本1秒就可以查询完毕的事情现在居然需要3-4分钟. 首先我的做法是先快速找出导致整个语句下降的元凶.在这个例子里面查询语句有3个JOIN字句,我通过删除某一个JOIN节点 ...
- 使用JSONP彻底解决Ajax跨域访问Cookie Session的方案
最近做开发时要把图片文件放到另外一台服务器上(另外一个域名),因为这样分布式存放,网站打开速度会快很多.而我采用AJAX获取图片服务器上某用户的图片时遇到了问题,按照通常的方式无法获取信息,得到的Co ...
- .net 的page的OnInit方法
/// <summary> /// 重写父类的方法,父类要执行的方法已经被覆盖 /// </summary> /// <param name="e"& ...