HttpClient.请求参数
有时候因为网络,或者目标服务器的原因,请求需要更长的时间才能完成,我们需要自定义相关时间
package cn.csdn.crawlar.test;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpConfigTest {
public static void main(String[] args) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet对象,设置url访问地址
String uri =
HttpGet httpGet = new HttpGet(uri);
//配置请求信息
RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout( 1000 );//创建链接的最长时间,单位毫秒
config.setConnectionRequestTimeout( 500 );//设置获取链接的最长时间,单位毫秒
config.setSocketTimeout( 10*1000 );//设置数据传输的最长时间,单位毫秒
config.build();
//给请求设置请求信息
httpGet.setConfig( RequestConfig.custom().build());
//try/catch/finally : Ctrl+Alt+T
CloseableHttpResponse response = null;
try {
//使用HttpClient发起请求,获取response
response = httpClient.execute(httpGet);
//解析响应
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "utf8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭response
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
日常生活中我们会遇到网络问题导致爬取不能立即完成,这时我们就需要通过配置请求的设置建立延时连接。
//配置请求信息
//创建链接的最长时间,单位毫秒
RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout( 1000 );
//设置获取链接的最长时间,单位毫秒
config.setConnectionRequestTimeout( 500 );
//设置数据传输的最长时间,单位毫秒
config.setSocketTimeout( 10*1000 );
config.build();
//给请求设置请求信息
httpGet.setConfig( RequestConfig.custom().build());