我应该如何处理Android应用中的http帖子的服务器超时和错误代码响应?

Aak*_*ash 7 php java android http

我的Android应用程序会对http://example.com/abc.php?email=abc@xyz.com等网址发送http帖子. 因此,Android应用程序基本上与服务器端的PHP进行对话并接收JSON响应并解析它们以填充各种应用程序中的视图.工作良好.

我的问题是 - 我应该如何处理Android App中的以下事件,以便在服务器端应用程序中发生这些事件时,应用程序不应该像现在那样强制关闭.

  1. 服务器超时发生且未收到响应.App力量现在关闭.我想妥善处理这件事.

  2. 作为对应用程序http帖子的响应返回到服务器的错误代码.App Force目前关闭,因为我没有处理这个问题.

我遇到过这两种情况,其中App未编码来处理这些事件.请随意添加可能导致可能导致Android应用程序出现ANR的任何其他事件.

一个小的代码片段或线索将帮助我很多,因为我以前从未这样做过.

谢谢.

Tha*_*hem 8

到目前为止添加了非常好的建议......

我的工作伙伴教我使用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.
Run Code Online (Sandbox Code Playgroud)