httpリクエストカード死の処理について
1752 ワード
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 futureTask = new FutureTask(
new Callable() {// 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;
}