引言
本文主要记录如何构建HttpClient(4.5.x) 和 入门使用.
参考官方文档
http://hc.apache.org/httpcomponents-client-4.5.x/current/tutorial/html/
1. HttpClient构建
1.1 关于HttpClinet
在构建之前, 先大致了解一下HttpClient类
HttpClient子类
DecompressingHttpClient: 装饰器类(已弃用),支持解压缩逻辑,可用RequestAcceptEncoding/ResponseContentEncoding取代.AutoRetryHttpClient: 装饰器类(已弃用),支持服务异常重试逻辑,可用ServiceUnavailableRetryStrategy取代.- CloseableHttpClient: 默认的HttpClient
- MinimalHttpClient: 简易版HttpClient
AbstractHttpClient: 已弃用,文档推荐HttpClientBuilder, 构建InternalHttpClient对象.- InternalHttpClient: 默认访问权限, 只能通过HttpClientBuilder构建.
经过上述说明, 4.5.x版本中, 我们只需关心如何通过HttpClientBuilder构建HttpClient即可.
此外,HttpClient还提供了HttpClients作为工厂类, 封装了HttpClientBuilder和MinimalHttpClient构建.
1.2 构建HttpClient(默认)
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(2000) // 创建Socket超时时间
.setConnectTimeout(2000) // 请求响应超时时间
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build()
2. HttpClient使用入门
2.0 构建URI
// 构建URI 方式1
URI uri = URI.create("http://localhost:8080/hello?user=roylion")
// 构建URI 方式2
URI uri = new URIBuilder("http://localhost:8080")
.setPath("/hello")
.addParameter("user", "roylion")
.build();
2.1 Get请求
基础GET请求
/**
* 基础get请求
*
* @param uri 请求路径
* @param headers 请求header参数 {@link BasicHeader#BasicHeader(String, String)}
* @param reqCfg 请求配置参数
* @return 返回响应, 用完必须close()
* @throws IOException
*/
public static CloseableHttpResponse baseGet(URI uri, Header[] headers, RequestConfig reqCfg) throws IOException {
final HttpGet httpGet = new HttpGet();
httpGet.setURI(uri);
httpGet.setHeaders(headers);
httpGet.setConfig(reqCfg);
return httpClient.execute(httpGet);
}
GET - FORM表单提交
/**
* form表单提交
*
* @param uri 请求路径
* @param formData 表单数据列表
* @return 响应结果
* @throws URISyntaxException
* @throws IOException
*/
public static String getFrom(URI uri, List<NameValuePair> formData) throws URISyntaxException, IOException {
URIBuilder uriBuilder = new URIBuilder(uri);
for (NameValuePair nameValuePair : formData) {
uriBuilder.addParameter(nameValuePair.getName(), nameValuePair.getValue());
}
URI finalUri = uriBuilder.build();
Header[] headers = new Header[]{new BasicHeader("Content-Type", "application/x-www-form-urlencoded")};
try (CloseableHttpResponse resp = baseGet(finalUri, headers, null);) {
return toString(resp.getEntity());
}
}
2.2 Post请求
基础POST请求
/**
* 基础post请求
*
* @param uri 请求路径
* @param headers 请求header参数 {@link BasicHeader#BasicHeader(String, String)}
* @param reqCfg 请求配置参数
* @param httpEntity 请求体对象
* String(文本, json...) {@link StringEntity}
* form(表单) {@link UrlEncodedFormEntity}
* multipartForm(文件, 图片, 文本...) {@link MultipartEntityBuilder#build()}
* @return 返回响应, 用完必须close()
* @throws IOException
*/
public static CloseableHttpResponse basePost(URI uri, Header[] headers, RequestConfig reqCfg, HttpEntity httpEntity) throws IOException {
HttpPost