使用HttpClient发送请求接收响应
1.一般需要如下几步:
(1) 创建HttpClient对象。
(2)创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
(3)
如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams
params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity
entity)方法来设置请求参数。
(4) 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
(5)
调用HttpResponse的getAllHeaders()、getHeaders(String
name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器
的响应内容。程序可通过该对象获取服务器的响应内容。
(6) 释放连接。无论执行方法是否成功,都必须释放连接
依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
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.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; public class HttpClientUtils { // HTTP内容类型。相当于form表单的形式,提交数据
public static final String CONTENT_TYPE_JSON_URL = "application/json;charset=utf-8"; // utf-8字符编码
public static final String CHARSET_UTF_8 = "utf-8"; // 连接管理器
private static PoolingHttpClientConnectionManager pool; // 请求配置
private static RequestConfig requestConfig; static { try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
builder.build());
// 配置同时支持 HTTP 和 HTPPS
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create
().register(
"http", PlainConnectionSocketFactory.getSocketFactory()).register(
"https", sslsf).build();
// 初始化连接管理器
pool = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// 将最大连接数增加到200,实际项目最好从配置文件中读取这个值
pool.setMaxTotal(200);
// 设置最大路由
pool.setDefaultMaxPerRoute(2); requestConfig = requestConfig(); } catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
} public static CloseableHttpClient getHttpClient() { CloseableHttpClient httpClient = HttpClients.custom()
// 设置连接池管理
.setConnectionManager(pool)
// 设置请求配置
.setDefaultRequestConfig(requestConfig)
// 设置重试次数
.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
.build(); return httpClient;
} /**
* 构建请求配置信息
* 超时时间什么的
*/
private static RequestConfig requestConfig() {
// 根据默认超时限制初始化requestConfig
int socketTimeout = 10000;
int connectTimeout = 10000;
int connectionRequestTimeout = 10000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout) // 创建连接的最长时间
.setConnectionRequestTimeout(connectionRequestTimeout) // 从连接池中获取到连接的最长时间
.setSocketTimeout(socketTimeout) // 数据传输的最长时间
.setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
.build();
return config;
} public static String doGetJson(String url, String param, Map<String, String> requestHead) {
String result = "";
CloseableHttpResponse response = null;
CloseableHttpClient httpclient = null;
try {
httpclient = getHttpClient();
URI uri = null;
if (param == null || param.equals("")) {
uri = new URIBuilder(url).build();
} else {
uri = new URIBuilder(url + "?" + param).build();
}
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig());
if (null != requestHead) {
for (Map.Entry<String, String> entry : requestHead.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpGet.addHeader(key, value);
}
}
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
result = decodeData(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
//不可以关闭,不然连接池就会被关闭
//httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
} public static String doPostJson(String url, String param, Map<String, String> requestHead) {
// 创建Httpclient对象
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(param, ContentType.APPLICATION_JSON);
entity.setContentType(CONTENT_TYPE_JSON_URL);
httpPost.setEntity(entity);
httpPost.setConfig(requestConfig());
if (null != requestHead) {
for (Map.Entry<String, String> entry : requestHead.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpPost.addHeader(key, value);
}
}
// 执行http请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
resultString = decodeData(resultString); } catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
} return resultString;
} public static String doGet(String url, Map<String, String> param, Map<String, String> requestHead) {
String result = "";
CloseableHttpResponse response = null;
CloseableHttpClient httpclient = null;
try {
String params = toHttpGetParams(param);
httpclient = getHttpClient();
URI uri = new URIBuilder(url + "?" + params).build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig());
if (null != requestHead) {
for (Map.Entry<String, String> entry : requestHead.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpGet.addHeader(key, value);
}
}
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
result = decodeData(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
} public static String doGet(String url, Map<String, String> param) {
return doGet(url, param, null);
} /**
* 根据实际需要决定是否需要解码
*/
static String decodeData(String base64Data) {
String str = "";
if (base64Data == null || base64Data.equals("")) {
str = "";
}
try {
String e = new String(Base64.decodeBase64(base64Data.getBytes(CHARSET_UTF_8)), CHARSET_UTF_8);
return e;
} catch (UnsupportedEncodingException var5) {
}
return str;
} /**
* 这里只是其中的一种场景,也就是把参数用&符号进行连接且进行URL编码
* 根据实际情况拼接参数
*/
private static String toHttpGetParams(Map<String, String> param) throws Exception {
String res = "";
if (param == null) {
return res;
}
for (Map.Entry<String, String> entry : param.entrySet()) {
res += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), CHARSET_UTF_8) + "&";
}
return "".equals(res) ? "" : StringUtils.chop(res);
} public static String doPost(String url, Map<String, String> param, Map<String, String> requestHead) {
// 创建Httpclient对象
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig());
if (null != requestHead) {
for (Map.Entry<String, String> entry : requestHead.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
httpPost.addHeader(key, value);
}
}
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), CHARSET_UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
} public static String doPost(String url, Map<String, String> param) { return doPost(url, param, null);
} public static String doPost(String url) {
return doPost(url, null);
} }
package com.winner; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.HashMap;
import java.util.Map; public class RestClient { public static final String GET = "GET";
public static final String POST = "POST"; private static Logger logger = LoggerFactory.getLogger(RestClient.class); private static Map<String, String> requestHeaders = new HashMap<String, String>() {{
put("Content-Type", "application/json");
put("charset", "UTF-8");
}}; public static String sendData(String url, String method, String param, Map<String, String> headers) {
logger.info("调用接口:{},方法:{}", url, method);
logger.info("参数:{}", param);
String returnStr = ""; if (headers != null) {
for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
headers.put(entry.getKey(), entry.getValue());
}
} else {
headers = requestHeaders;
}
try {
if (method.equals(GET)) {
returnStr = HttpClientUtils.doGetJson(url, param, headers); }
if (method.equals(POST)) {
returnStr = HttpClientUtils.doPostJson(url, param, headers);
}
} catch (Exception exception) {
logger.error("系统调用异常:", exception);
//注意,在Controller中进行捕捉
throw new BusinessException(00000, exception.getMessage());
}
logger.info("调用完成,返回值:{}", returnStr);
return returnStr;
}
}
使用HttpClient发送请求接收响应的更多相关文章
- 使用HttpClient发送请求、接收响应
使用HttpClient发送请求.接收响应很简单,只要如下几步即可. 1.创建HttpClient对象. CloseableHttpClient httpclient = HttpClients.c ...
- .NetCore HttpClient发送请求的时候为什么自动带上了一个RequestId头部?
奇怪的问题 最近在公司有个系统需要调用第三方的一个webservice.本来调用一个下很简单的事情,使用HttpClient构造一个SOAP请求发送出去拿到XML解析就是了. 可奇怪的是我们的请求在运 ...
- fiddler模拟发送请求和响应
iddler模拟发送请求和响应 一.fiddler模拟发送请求 1.fiddler模拟发送get请求 1)例如:访问博客园https://www.cnblogs.com/,并且登录输入密码账号登录,再 ...
- httpClient 发送请求后解析流重用的问题(HttpEntity的重用:BufferedHttpEntity)
使用场景: 项目中使用httpClient发送一次http请求,以流的方式处理返回结果,开始发现返回的流只能使用一次,再次使用就会出错,后来看了一些解决方案,EntityUtils.consume(r ...
- Postman使用手册1——导入导出和发送请求查看响应
导读: 现在的web和移动开发,常常会调用服务器提供restful接口进行数据请求,为了调试,一般会先用工具进行测试,通过测试后才开始在开发中使用.这里介绍一下如何在chrome浏览器利用postma ...
- 发送请求获取响应内容(c#)
C#请求url,获取响应的脚本 public string ResultOfApi(string url) { //发送请求 HttpWebRequest request = null; HttpWe ...
- HttpClient 发送请求和参数
发送请求 没有参数 private static void getData() { String timeStamp = String.valueOf(System.currentTimeMillis ...
- [java,2018-01-16] HttpClient发送、接收 json 请求
最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...
- 记录下httpclient 发送请求 服务端用@RequestBody 自动接收参数 报415
注解是post方式,那么检查以下内容:1. 你是否用了post请求2. 请求是否发送了数据3. 请求内容格式需要是 application/json .jquery 设置 contentType,-- ...
随机推荐
- jquery datatable的详细用法
1,首先需要引用下面两个文件 <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css ...
- 2017-2018-1 20179202《Linux内核原理与分析》第二周作业
本周着重学习了汇编指令,并通过反汇编C程序了解栈帧变化. 实践 看了孟老师的演示视频后,我重新写了C程序,如下: int main() { int a=1,b=2; return g(a,b); } ...
- CodeForces 785C Anton and Fairy Tale
二分. 如果$n≤m$,显然只能$n$天. 如果$n>m$,至少可以$m$天,剩余还可以支撑多少天,可以二分计算得到,也可以推公式.二分计算的话可能爆$long$ $long$,上了个$Java ...
- 洛谷P3434 [POI2006]KRA-The Disks [模拟]
题目传送门 KRA 题目描述 For his birthday present little Johnny has received from his parents a new plaything ...
- Python之路【第三篇】:文件操作
一.文件操作步骤 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 歌名:<大火> 演唱:李佳薇 作词:姚若龙 作曲:马奕强 歌词: 有座巨大的停了的时钟 倾倒在赶 ...
- 在eclipse中安装TestNG
https://www.cnblogs.com/baixiaozheng/p/4989856.html 1.可借助Eclipse的Marketplace来安装TestNG Eclipse插件 a.打开 ...
- FastReport.Net使用:[16]图片控件使用
FastReport中,图片(Picture)控件的用法? 支持的图片格式 1.BMP, PNG, JPG, GIF, TIFF, ICO, EMF, WMF 支持的数据源 支持图片,数据列,文件名, ...
- Codeforces 1129 E.Legendary Tree
Codeforces 1129 E.Legendary Tree 解题思路: 这题好厉害,我来复读一下官方题解,顺便补充几句. 首先,可以通过询问 \(n-1\) 次 \((S=\{1\},T=\{ ...
- WEB架构师成长之路 二
法宝一:牛人爱惜自己的时间. 时间就是金钱,时间就是生命,时间如同健康一样,如果时间都没有,那成功也就是浮云了.所以牛人总是很爱惜自己的时间,总是在想办法提高自己的做事效率.我突然想了起来,我QQ里有 ...
- AOP:声明式事务管理流程
1. 注册BeanFactoryTransactionAttributeSourceAdvisor @EnableTransactionManagement --> @Import(Transa ...