使用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 ...
随机推荐
- Python Django 路由分发
mysite1 为一个django工程 cmdb为一个项目 dashboard为一个项目 在mysite1工程下的urls.py中定义如下: from django.conf.urls import ...
- 001Spring Boot中使用MongoDB
01.下载MongoDB 点击标题链接,下载windows可用的MongoDB. 02.解压 将下载的压缩包放入C盘根目录(根据自己需要调整目录)---->解压到当前文件夹---->重命名 ...
- LeetCode赛题392---- Is Subsequence
392. Is Subsequence Given a string s and a string t, check if s is subsequence of t. You may assume ...
- 单选按钮(RadioButton)
一:RadioButton的相关属性: 1.Activity //单选按钮 public class RadioButtonActivity extends Activity { private Co ...
- MultiThread(VS2013 MFC多线程-含源码-含个人逐步实现文档)
原文:http://download.csdn.net/download/jobfind/9559162 MultiThread(VS2013 MFC多线程-含源码-含个人逐步实现文档).rar
- Android的事件分发(dispatchTouchEvent),拦截(onInterceptTouchEvent)与处理(onTouchEvent)
在Android中,View的结构是树状的,所以,当触发触摸事件的时候,其事件传递也是从上之下一层层的传递.下面我们结合例子来一点点进行分析. 首先,我们需要了解事件处理中的几个方法: 1.在View ...
- 下载MySQL的各个历史版本
MYSQL官方archives链接地址:http://downloads.mysql.com/archives/community/
- Spring MVC基本配置和实现(三)
Item public class Item { private Integer id; private String name; public Integer getId() { return id ...
- Spring MVC基本配置和实践(二)
1. springmvc: 是一个表现层框架,作用是从请求中接收传入的参数,将处理后的结果数据返回给页面展示 2. ssm整合: 1)Dao层 pojo.mapper接口.mapper映射文件(使用逆 ...
- Python 装饰器的总结
先来了解几个定义: 1,函数 在python中,函数通过def关键字.函数名和可选的参数列表定义.通过return关键字返回值.我们举例来说明如何定义和调用一个简单的函数: #coding:UTF8 ...