【发布时间】:2012-09-10 08:07:33
【问题描述】:
我正在尝试连接到必须获取数据的互联网,如果连接时间超过 5 秒,我必须完成该过程并继续离线工作。
一切正常,有时在互联网不可用时大约需要 10 秒到return,现在我必须在时间超过时间限制时返回xml == null;,
我不想在异步任务中这样做
public String getUrlData(String url) {
String xml = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
// check if the timer has exceeded by "if else"
// move to "return xml;" Manually when exceeds 5sec, but how?
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xml;
}
this answer之后的编辑代码
public String getUrlData(String url) {
String xml = null;
final int TIMEOUT_MILLISEC = 5000; // 5 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost = new HttpPost(url);
System.out.println("waiting");
HttpResponse httpResponse;
try {
// start the timer here
System.out.println("Started");
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Ended");
return xml;
}
LogCat 在这里 >> 20 Secs
【问题讨论】:
-
你是在真机还是模拟器上试过这个?在尝试使用 DefaultHttpClient 时,我注意到设置超时在模拟器中无法正常工作。它基本上只是忽略任何超时设置(另见this post)
-
但是,我的要求不是这样,我需要一些东西来跳过我在 5 秒后执行 HTTP 请求并将 xml 返回为空。如果 xml 在 5 秒前返回,那么什么都不会发生。
-
如果您按照 Waqas 的建议设置超时,您的 http-request 将在超时间隔后自动停止并抛出错误。您所要做的就是捕获错误并返回 null。我的观点是,这只适用于真实设备,而不适用于模拟器。
标签: java android multithreading concurrency