return false;
}
if (exception instanceof ConnectException)
{
// Connection refused
return false;
}
if (exception instanceof SSLException)
{
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent)
{
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
client.setHttpRequestRetryHandler(myRetryHandler);
DefaultHttpClient client = new DefaultHttpClient(cm);
Integer socketTimeout = 10000;
Integer connectionTimeout = 10000;
final int retryTime = 3;
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
client.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY, false);
client.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 1024 * 1024);
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler()
{
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context)
{
if (executionCount >= retryTime)
{
return false;
}
if (exception instanceof InterruptedIOException)
{
// Timeout
return false;
}
if (exception instanceof UnknownHostException)
{
// Unknown host
return false;
}
if (exception instanceof ConnectException)
{
// Connection refused
return false;
}
if (exception instanceof SSLException)
{
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent)
{
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
client.setHttpRequestRetryHandler(myRetryHandler);
5、6行分别设置了Socket最大等待时间、连接最大等待时间(单位都是毫秒)。socket等待时间是指从站点下载页面和数据时,两个数据包之间的最大时间间隔,超过这个时间间隔,httpclient就认为连接出了故障。连接最大等待时间则是指和站点建立连接时的最大等待时间,超过这个时间站点不给回应,则认为站点无法连接。第7行设置httpclient不使用NoDelay策略。如果启用了NoDelay策略,httpclient和站点之间传输数据时将会尽可能及时地将发送缓冲区中的数据发送出去、而不考虑网络带宽的利用率,这个策略适合对实时性要求高的场景。而禁用了这个策略之后,数据传输会采用Nagle's algorithm发送数据,该算法会充分顾及带宽的利用率,而不是数据传输的实时性。第8行设置socket缓冲区的大小(单位为字节),默认是8KB。
HttpRequestRetryHandler是负责处理请求重试的接口。在该接口的内部类中实现RetryRequest方法即可。当httpclient发送请求之后出现异常时,就会调用这个方法。在该方法中根据已执行请求的次数、请求内容、异常信息判断是否继续重试,若继续重试返回true,否则返回false。
3、设置request header
设置request header也是很重要的,比如设置User-Agent可以将抓取程序伪装成浏览器,骗过一些网站对爬虫的检查,设置Accept-Encoding为gzip可以建议站点以压缩格式传输数据、节省带宽等等。例程如下:
[java]
HttpResponse response = null;
HttpGet get = new Htt