大家在做http请求时可能会遇到这种情况,明明设置了connetTimeOut和SocketTimeOut可是在实际使用的过程中却还是无法在设置的时间内得到响应结果(正确的或者异常的),请求就一直处于卡死状态,这种情况在手机端会比较常见(特别是网络环境不佳的时候),具体原因暂时不知,但我们可以对这种情况做下处理,这样不至于导致app处于一直等待的卡死状态。使用FutureTask对请求做定时处理,在限定时间内返回返回结果,不管http请求是否完成。一般我们可以把FutureTask的时间限定的长一些,一般足以让http请求正常返回就行。下面上代码
public static HttpResult proc(HttpClient client, HttpUriRequest req, Charset charset, int count) throws Exception
{
ExecutorService executor = Executors.newSingleThreadExecutor();
FutureTask<HttpResponse> futureTask = new FutureTask<HttpResponse>(
new Callable<HttpResponse>() {// 使用Callable接口作为构造参数
public HttpResponse call() {
HttpResponse response = null;
try {
response = client.execute(req);
} catch (Exception e) {
}
return response;
}
});
executor.execute(futureTask);
HttpResponse response = null;
try {
// 这里是限定2分钟内
response = futureTask.get(120000, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
futureTask.cancel(true);
} finally {
executor.shutdown();
}
if(response == null) {
return new HttpResult(response, req);
}
if (response.getStatusLine().getStatusCode() == 302 || response.getStatusLine().getStatusCode() == 301)
{
Header header = response.getFirstHeader("Location");
if (header != null)
{
String location = header.getValue();
System.out.println("location:" + location);
HttpGet get = new HttpGet(location);
return proc(client, get, StandardCharsets.UTF_8, count);
}
return new HttpResult(response, req, charset);
}
HttpResult rh = new HttpResult(response, req, charset);
return rh;
}