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" ...

  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的简单使用_向前台发送JSON数据

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

  7. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

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

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

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

  9. 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 ...

随机推荐

  1. bat批处理中如何获取前一天日期

    网上找了好久在批处理中生成前一日期的代码段 但网上找到的代码对 每个月的1号和每年的1号计算前一日期时,总会报错,然后要加很多的逻辑判断 想了想,可以用.net写个EXE程序,用.net实现获取前一日 ...

  2. CSS(一)sytle

    一:CSS语法组成:  选择符 和声明(声明和声明之间用分号隔开)  声明部分:属性和属性值(用冒号链接)  语法:选择符{   属性1:属性值:   属性2:属性值:  } 所有的CSS语句都要放到 ...

  3. css3怎么分清伪类和伪元素

    伪类用于向某些选择器添加特殊的效果. 伪元素用于将特殊的效果添加到某些选择器. 伪类有::first-child ,:link:,vistited,:hover,:active,:focus,:lan ...

  4. Eclipse调试不能进入断点

    Eclipse下在给行设置断点或者在调试时弹出错误“Unable to install breakpoint due to missing line number attributes,Modify ...

  5. 2.bootstrap安装

    1.下载 您可以从 http://getbootstrap.com/ 上下载 Bootstrap 的最新版本(或者 http://www.bootcss.com/  中文网) Download Boo ...

  6. 自创open vp n windows步骤

    Easy Windows Guide¶ This page contains a no-frills guide to getting OpenVPN up and running on a Wind ...

  7. java获取文件大小的方法

    目前Java获取文件大小的方法有两种: 1.通过file的length()方法获取: 2.通过流式方法获取: 通过流式方法又有两种,分别是旧的java.io.*中FileInputStream的ava ...

  8. c#多线程调用有参数的方法

      Thread (ParameterizedThreadStart) 初始化 Thread 类的新实例,指定允许对象在线程启动时传递给线程的委托.   Thread (ThreadStart) 初始 ...

  9. 解决网卡无法自动获取ip的办法

    解决网卡无法自动获取IP址的方法          为了省钱或者一户多机,很多人都购买宽带路由器共享上网.在架设路由上网的时候,有些“师傅”可能不懂或是偷懒,开启了宽带路由器的DHCP( Dynami ...

  10. css动画 文字闪烁效果

    /*定义页面基础CSS*/ body{ font-family: 'microsoft yahei',Arial,sans-serif; color: #EFEFEF; background: #22 ...