标签:static custom null tar 编程工具 out article tostring iba
HttpClient是支持Http协议的客户端编程工具包。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
public static void main(String[] args) {
//创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet实例
HttpGet httpGet = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = null;
//执行Get请求
try {
response = httpClient.execute(httpGet);
//获取实体
HttpEntity httpEntity = response.getEntity();
//解析实体
System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
HttpClient内部有三个超时时间设置:连接池获取可用连接超时,连接超时,读取数据超时
先连接,后读取。
RequestConfig requestConfig = RequestConfig.custom()
//从连接池中获取连接的超时时间
.setConnectTimeout(5000)
//httpclient会创建一个异步线程用以创建socket连接,此处设置该socket的连接超时时间
.setConnectionRequestTimeout(1000)
//socket读数据超时时间:从服务器获取响应数据的超时时间
.setSocketTimeout(5000)
.build();
httpGet.setConfig(requestConfig);
HttpClient源码解析系列:第二篇:极简版实现
HttpClient官网 Quick Start
标签:static custom null tar 编程工具 out article tostring iba
原文地址:https://www.cnblogs.com/fonxian/p/10855973.html