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. JDBC入门(4)--- 批处理

    1.Statement批处理 当你有10条SQL语句要执行时,一次向服务器发送一条SQL语句,这样做的效率上极差,处理的方案是使用批处理,即一次向服务发送多条SQL语句,然后由服务器一次性处理. 批处 ...

  2. C#学习笔记-模板方法模式

    题目:同学摘抄老师给的试卷并给出自己的对应的答案. 实现: static void Main(string[] args) { Console.WriteLine("学生甲抄的试卷:&quo ...

  3. sublime Text3汉化和激活注册码

    sublimeText3 很不错,前面几天下了vscore学习Node.js,感觉有点懵,今天下载sublimeText3,遇到的一些小问题,在这里说说: 百度云:https://pan.baidu. ...

  4. csharp:Conversion Between DataTable and List

    /// <summary> /// http://www.codeproject.com/Tips/784090/Conversion-Between-DataTable-and-List ...

  5. 设计模式 UML & java code

    A: 创造性模式 1. 工厂方法模式(FactoryMethod) 1.1 类图 1.2 代码1 public interface Pet { public String petSound(); } ...

  6. Aizu2292 Common Palindromes

    题意 我也不知道哪里来的OJ \(vjudge\) 上的 给定两个字符串 \(S,T\) ,询问 \((i,j,k,l)\) 这样的四元组个数 使得 \(S[i,j],T[k,l]\) 是相等的回文串 ...

  7. MyEclipse打包带源码的jar包

    平时开发中,我们喜欢将一些类打包成jar包,然后在别的项目中继续使用,不过由于看不到jar包里面的类的源码了,所以也就无法调试,要想调试,那么就只能通过关联源代码的形式,这样或多或少也有一些不方便,今 ...

  8. can't start Git: git.exe

    can't start Git: git.exe :不能启动Git 这是因为Git的可执行文件的路径不正确,需要手动设置,. 找到设置Git的窗口 然后修改一下路径就行了 点击OK就可以了.

  9. Raspberry install wine

    sudo apt install wine winecfg出现问题 树莓派3B是卡片电脑,内存为1GB,一般运行Linux.Linux两种主流的内存分配方法2G/2G和3G/1G,树莓派系统后期优化性 ...

  10. 使用Netty3或Netty4发布Http协议服务

    现在是2018年1月11日18:12分,已经是下班时间了,小Alan今天给大家简单的介绍一下Netty,让大家以后在使用到Netty的时候能够有一定的了解和基础,这样深入学习Netty以及以后灵活应用 ...