使用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,-- ...
随机推荐
- Java学习(if wihle switch for语句)
一.if语句 定义:if语句是指如果满足某种条件,就进行某种处理. 语句: if (条件语句){ 执行语句; …… } 上述格式中,判断条件是一个布尔值,当判断条件为true时,{}中的执行语句才会执 ...
- 【PAT】1010. 一元多项式求导 (25)
1010. 一元多项式求导 (25) 设计函数求一元多项式的导数.(注:xn(n为整数)的一阶导数为n*xn-1.) 输入格式:以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数 ...
- spring_150901_hibernate_transaction_xml
实体类: package com.spring.model; import javax.persistence.Entity; import javax.persistence.Id; import ...
- 报错org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet"
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n ...
- phpstorm+xdebug远程调试设置
1 xdebug扩展安装 1.1 xdebug扩展安装: 2 服务器PHP配置 3 phpstorm设置 3.1 添加远程debug 3.2 phpstorm设置: 4 浏览器插件安装 4.1 chr ...
- YAHOO 35条前端优化建议(转)
Yahoo!的 Exceptional Performance团队为改善 Web性能带来最佳实践.他们为此进行了一系列的实验.开发了各种工具.写了大量的文章和博客并在各种会议上参与探讨.总结出了一系列 ...
- perl相关知识
转:http://www.runoob.com/perl/perl-cgi-programming.html Perl 是 Practical Extraction and Report Langua ...
- PHP变量的使用
如果在用到数据时,需要用到多次就声明为变量使用: 变量的声明 $变量名=值 强类型语言中(C,Java),声明变量一定要先指定类型(酒瓶) PHP是弱类型的语言:变量的类型有存储的值决定.(瓶子) 2 ...
- 斐波那契数列(python实现)
描述 一个斐波那契序列,F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) (n>=2),根据n的值,计算斐波那契数F(n),其中0≤n≤1000. 输入 输入 ...
- bzoj 1779
较水的网络流. /************************************************************** Problem: 1779 User: idy002 L ...