我正在尝试连接到必须获取数据的互联网,如果连接时间超过 5 秒,我必须完成该过程并继续离线工作。
一切正常,有时return
互联网不可用大约需要 10 秒,现在我必须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;
}
此答案后编辑的代码
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 秒