[英]How should I handle server timeouts and error code responses to an http post in Android App?
我的Android應用程序會對http://example.com/abc.php?email=abc@xyz.com等網址發送http帖子。因此,Android應用程序基本上與服務器端的PHP進行對話並接收JSON響應並解析它們以填充各種應用程序中的視圖。 工作良好。
我的問題是 - 我應該如何處理Android App中的以下事件,以便在服務器端應用程序中發生這些事件時,應用程序不應該像現在那樣強制關閉。
服務器超時發生且未收到響應。 App力量現在關閉。 我想妥善處理這件事。
作為對應用程序http帖子的響應返回到服務器的錯誤代碼。 App Force目前關閉,因為我沒有處理這個問題。
我遇到過這兩種情況,其中App未編碼來處理這些事件。 請隨意添加可能導致可能導致Android應用程序出現ANR的任何其他事件。
一個小的代碼片段或線索將幫助我很多,因為我以前從未這樣做過。
謝謝。
到目前為止添加了非常好的建議......
我的工作伙伴教我使用org.apache.http包中的類,如下所示:
String result = null;
HttpGet request = new HttpGet(some_uri);
// As Jeff Sharkey does in the android-sky example,
// use request.setHeader to optionally set the User-Agent header.
HttpParams httpParams = new BasicHttpParams();
int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS);
HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
HttpClient client = new DefaultHttpClient(httpParams);
try
{
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK)
{
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = responseHandler.handleResponse(response);
}
else
{
// Do something else, if wanted.
}
}
catch (ClientProtocolException e)
{
Log.e(LOG_TAG, "HTTP Error", e);
// Do something else, if wanted.
}
catch (IOException e)
{
Log.e(LOG_TAG, "Connection Error", e);
// Do something else, if wanted.
}
finally
{
client.getConnectionManager().shutdown();
}
// Further parse result, which may well be JSON.
正如Kaj在評論中所說,一種選擇是捕獲異常,並且可能重試或發布失敗消息。
對於響應代碼!= 200,只需讀取它們就可以在if (con.getResponseCode() == 200)
塊內完成工作
另一種選擇是使用更好的Apache類:
http://developer.android.com/reference/org/apache/http/package-summary.html
對於一個片段,請在SO中檢查BalusC的教程: 使用java.net.URLConnection來觸發和處理HTTP請求
您還應該確保在UI線程中沒有像HTTP請求那樣執行冗長的任務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.