我尝试从 POST 请求中获取响应。问题是,尽管我正在使用 AsyncTask 进行网络通信,但有时我会得到 NetworkOnMainThreadException。这意味着有时我成功获得响应,有时我得到这个异常。
这是我的 HTTP POST 请求 AsyncTask:
static class HTTPPostRequest extends AsyncTask<PostRequestParams, Void, AsyncResponse> {
@Override
protected AsyncResponse doInBackground(PostRequestParams... params) {
AsyncResponse retVal = new AsyncResponse();
HttpClient client = getHttpClient();
UrlEncodedFormEntity formEntity = null;
HttpPost request = new HttpPost();
try {
request.setURI(new URI(params[0].URL));
formEntity = new UrlEncodedFormEntity(params[0].params);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
retVal.setOutput(response);
} catch (ClientProtocolException e) {
retVal.setException(e);
} catch (IOException e) {
retVal.setException(e);
} catch (URISyntaxException e) {
retVal.setException(e);
}
return retVal;
}
}
以及实际调用它的代码:
AsyncResponse response = new AsyncResponse();
PostRequestParams postParams = new PostRequestParams();
postParams.URL = URL + "login.php";
postParams.params.add(new BasicNameValuePair("username", username));
postParams.params.add(new BasicNameValuePair("password", password));
try {
response = new HTTPPostRequest().execute(postParams).get();
if (response.getException() != null) {
return "Error";
}
HttpResponse httpResponse = (HttpResponse) response.getOutput();
if (httpResponse.getStatusLine().getStatusCode() != 200) {
return "Error " + httpResponse.getStatusLine().getStatusCode();
}
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
} catch (InterruptedException | ExecutionException | IllegalStateException | IOException e) {
response.setException(e);
return null;
}
最佳答案
您应该移动处理 InputStream 的代码,例如:
return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));
还有你的 AsyncTask。您不想在 UI 线程中处理 InputStreams。
关于java - NetworkOnMainThreadException 有时会抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22416743/