2013-01-04 70 views
1

我正在向android應用程序的cgi php服務器發出HTTP請求以獲取json響應。 我的應用程序正在驗證互聯網連接是否可用,然後再發出HTTP請求。高興這一切都正常工作。問題是我在 有時因爲發出HTTP請求後因特網連接突然死亡而關閉。Http響應錯誤android

所以我的問題是

  1. 我怎麼知道我是從服務器的響應?
  2. 我是否需要保持冷靜的迴應?
+4

請你可以用logcat發佈一些代碼嗎? – GrIsHu

+0

連接到遠程服務器時,您需要檢查很多事情。只檢查互聯網連接是不夠的。郵政編碼以及logcat輸出。 – Kanth

+3

'因爲發出http請求後互聯網連接突然死亡,所以有時候關閉了一個部隊。' - 爲你的Http請求始終設置連接和套接字超時,並且處理這個異常是最好的方法。 – user370305

回答

5

這裏是我的Web請求完美運行代碼處理

public JSONObject connectToService(String url, final Context context) { 

    try { 
     if(!isConnected(context)){ 
      return; 
     } 

     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 

     HttpParams httpParameters = httpGet.getParams(); 
     // Set the timeout in milliseconds until a connection is established. 
     int timeoutConnection = 7500; 
     HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
     // Set the default socket timeout (SO_TIMEOUT) 
     // in milliseconds which is the timeout for waiting for data. 
     int timeoutSocket = 7500; 
     HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

     HttpResponse httpResponse = httpClient.execute(httpGet); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     InputStream is = httpEntity.getContent(); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 

     String jsonString = sb.toString(); 
     Log.e("WebServiceHandler", "JSON string returned is"+jsonString.toString()); 

     JSONObject jsonObject = new JSONObject(jsonString); 
     return jsonObject; 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (SocketTimeoutException e) { 
     e.printStackTrace(); 
    } catch (ConnectTimeoutException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

     return null; 
} 

public boolean isConnected(Context context) { 
    ConnectivityManager connMgr = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     return true; 
    } else { 
     return false; 
    } 
} 

這個代碼是GET請求,如果您想擊中帖子的網址請求然後簡單地改變這一行相應

HttpGet httpGet = new HttpGet(url); 

HttpPost httpPost = new HttpPost(url); 
+0

其工作完美... –

0

首先將所有HTTP進程設置爲asyncTask,因爲它可能由於連接速度較慢而導致ANR(應用程序未響應)強制關閉,然後執行適當的特殊處理。 服務器響應可以用下面的代碼進行檢查:

HttpClient httpclient = new DefaultHttpClient(httpParameters); 

     HttpGet httpget = new HttpGet(url + encodedData); 

     response = httpclient.execute(httpget);