2013-04-21 74 views
2

我的活動使用AsynTask執行http請求。 如果Web服務器不回答,如何處理HttpResponse? 當前當我的網絡服務器關閉時,AsynTask停止在「HttpResponse response = client.execute(httppost);」然後什麼都不做。我需要處理這個響應並做一些事情,但是下面的代碼「execute」不會被執行。如何在AsyncTask中處理HttpResponse android

這裏是紐約後臺任務:

protected String doInBackground(String... params) { 
     HttpClient client = new DefaultHttpClient(); 
     String result = null; 
     try { 
      // Add your data 
      List<NameValuePair> postData = new ArrayList<NameValuePair>(2); 
      postData.add(new BasicNameValuePair("session_id", session_id)); 
      postData.add(new BasicNameValuePair("i_key", params[0])); 

      HttpPost httppost = new HttpPost("http://my.webserver.com/getInfo.php"); 
      httppost.setEntity(new UrlEncodedFormEntity(postData)); 

      HttpResponse response = client.execute(httppost); 
      HttpEntity responseEntity = response.getEntity(); 
      if (responseEntity != null) { 
       BufferedReader reader = new BufferedReader(
         new InputStreamReader(responseEntity.getContent(), 
           "UTF-8")); 
       result = reader.readLine().toString(); 
      } else { 
       Toast.makeText(this, "DDDDDDD",Toast.LENGTH_LONG).show(); 
      } 

     } catch (IllegalArgumentException e1) { 
      e1.printStackTrace(); 
     } catch (IOException e2) { 
      e2.printStackTrace(); 
     } 
     return result; 
    } 

如何,如果Web服務器已關閉,沒有回答我能處理的響應?

+0

1分鐘後您是否超時異常? – Adil 2013-04-21 17:05:14

+0

如果您的網絡服務器沒有關閉/不回覆,請設置超時,之後您將收到超時異常。試一試,http://stackoverflow.com/questions/16098810/access-network-availability-state-android/16099100#16099100 – surender8388 2013-04-21 17:10:27

+0

你不應該使用AsyncTask來執行網絡請求,因爲當你的設備的方向改變活動被破壞,但也是與此活動的生命週期相關的AsyncTask。爲了避免這種情況,應該使用服務模式。 – Pcriulan 2013-04-24 19:43:19

回答

3

您需要爲客戶端的連接設置超時。例如:

protected String doInBackground(String... params) { 
    HttpParams httpParameters = new BasicHttpParams(); 
    // set the connection timeout and socket timeout parameters (milliseconds) 
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); 
    HttpConnectionParams.setSoTimeout(httpParameters, 5000); 

    HttpClient client = new DefaultHttpClient(httpParameters); 
    . . . // the rest of your code 
}