有时会抛出NetworkOnMainThreadException

时间:2014-03-14 22:16:18

标签: java android android-asynctask

我尝试从POST请求获得响应。问题是有时我得到了NetworkOnMainThreadException,尽管我使用AsyncTask进行网络通信。这意味着有时我会成功获得响应,有时我会得到此异常。

这是我的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;
    }

1 个答案:

答案 0 :(得分:4)

您应该移动处理InputStream的代码,例如:

 return (String) formatResponse(new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())));

也是你的AsyncTask。处理InputStreams不是你想要在UI线程中做的事情。