我想設置超時,如果數據在15秒內無法獲取。我使用異步方法從服務器獲取數據。我嘗試了一些代碼中顯示的內容。我使用get(15000, TimeUnit.MILLISECONDS);
,它等待15秒,並斷開連接,仍然可以在15秒內獲得數據。我還使用了定時器doInBackground()
,但它有同樣的問題。 我想超時15秒,如果數據無法及時獲取,就會顯示'連接問題'對話框。請提前幫助我。Android如何設置超時延遲響應異步get方法
類
class GetTAsk extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... uri) {
//HttpParams params = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(params,15000);
//HttpConnectionParams.setSoTimeout(params,15000);
//DefaultHttpClient client = new DefaultHttpClient(params);
HttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet(uri[0]);
//httpGet.setParams(params);
HttpResponse response = null;
String responseString = null;
requestTime = new Date();
Log.i(l,"URL: "+uri[0]);
try {
response = httpClient.execute(httpGet);
Log.i(l,""+response.getStatusLine().toString());
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*new Timer().schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
httpGet.abort();
Log.e("LOG","request aborted");
progressBar.cancel();
cancel();
}
},1000);
*/
try {
get(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isCancelled()) {
Log.e("LOG","the task is cancelled");
progressBar.cancel();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
這一行工作我 - HttpConnectionParams.setConnectionTimeout(httpParameters,TIMEOUT); HttpConnectionParams.setSoTimeout(httpParameters,SO_TIMEOUT) – Ravi
@ rb16是的,我試過了,但它不能正常工作 –
爲什麼你評論這些行: // HttpParams params = new BasicHttpParams(); //HttpConnectionParams.setConnectionTimeout(params,15000); //HttpConnectionParams.setSoTimeout(params,15000); 您是否嘗試過包含上述代碼的代碼? –