概述
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。
虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
环境
最常用的http请求库是httpcomponents,为了方便处理json数据,导入阿里的fastjson。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<!--如果需要灵活的传输文件,引入此依赖后会更加方便-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
入门
使用步骤:
- 创建HttpClient对象
- 创建HttpPost或者HttpGet请求
- 为HttpPost设置header和config
- 如果post请求有参数,先设置post请求参数,get请求直接拼到url后面就可以了
- 使用HttpClient执行(execute)get、post请求
- 拿到responseEntity,使用EntityUtils工具类解析responseEntity内容
Get请求
public static JSONObject httpGet(String url) {
//1.创建httpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
try {
//2.封装、发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
//3.读取服务器返回过来的json字符串数据
String result = EntityUtils.toString(response.getEntity());
return jsonResult;
}
Post请求
/**
* post请求,第二个参数表示post请求参数
*/
public static JSONObject httpPost(String url, String jsonStr) {
//1. 创建httpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
JSONObject jsonResult = new JSONObject();
//2. 封装post请求
HttpPost method = new HttpPost(url);
//3. 进行配置
method.setConfig(getRequestConfig());
//4. 设置header
//5. 设置post请求参数
StringEntity entity = new StringEntity(jsonStr, "utf-8");
method.addHeader("content-type", "application/json");
method.setEntity(entity);
//6. 发送post请求,解析参数
HttpResponse result = httpClient.execute(method);
String str = EntityUtils.toString(result.getEntity());
}
// 设置超时时间
public static RequestConfig getRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(10000)
.setSocketTimeout(35000)
.setConnectionRequestTimeout(6000)
.build();
}
HttpClient连接池
在处理高并发情况的时候最好设置一下HTTP连接池,因为创建HTTP连接是非常耗时的。
//创建HttpClient对象并配置连接池
public static CloseableHttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
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();
// 初始化连接管理器
poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 同时最多连接数
poolConnManager.setMaxTotal(640);
// 设置最大路由
poolConnManager.setDefaultMaxPerRoute(320);
return HttpClients.custom()
.setConnectionManager(poolConnManager)
.build();
}