这几天写了一个爬虫,使用的是HttpClient,但是在爬的时候,总会出现爬到中途,程序就停在那,不往下爬了,也不报错,并且每次停止的位置也不一样,很是奇怪,于是进行debug发现是卡在了httpClient.execute这里,再深入发现是卡在了SocketInputStream类的socketRead0方法这里。
其实问题就是请求不到数据,一直卡在这,可能是由于请求过于频繁或者是网络问题。加上一个超时的限制就行了,加上以后,如果请求超时,重新请求即可。
主要是修改一下httpclent的配置。
int socketTimeout = 15000;//读取数据超时
int connectTimeout = 15000;//链接超时
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(false)
.setSoLinger(1)
.setSoReuseAddress(true)
.setSoTimeout(10000)
.setTcpNoDelay(true).build();
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(connectTimeout).build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultSocketConfig(socketConfig)
.setDefaultRequestConfig(config).build();
/* HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build();*/
用这种方法来创建HttpClient即可。