我的 Android 应用程序将 http 帖子发送到像 http://example.com/abc.php?email=abc@xyz.com 这样的 URL 因此,Android 应用程序基本上与服务器端的 PHP 对话并接收 JSON 响应并解析它们以填充应用程序中的各种 View 。工作正常。
我的问题是 - 我应该如何处理 Android 应用程序中的以下事件,以便万一这些事件发生在服务器端应用程序中,应用程序不应像现在这样强制关闭。
发生服务器超时,未收到任何响应。 App 强制关闭。我想妥善处理这件事。
作为对发送到服务器的应用程序 http 发布的响应而返回的错误代码。 App Force 目前关闭,因为我还没有处理这个问题。
我遇到过这两种情况,App 没有编码来处理这些事件。请随时添加任何其他可能导致 Android 应用出现 ANR 的事件。
一点代码 fragment 或线索会对我有很大帮助,因为我以前从未这样做过。
谢谢。
最佳答案
添加到目前非常好的建议...
我的同事教我像这样使用 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.
关于java - 我应该如何处理服务器超时和对 Android 应用程序中的 http 帖子的错误代码响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5941515/