java - NetworkOnMainThreadException 有时会抛出

标签 java android android-asynctask

我尝试从 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/

相关文章:

android - Asynctask 无法将变量从 doInBackground 传递到 onPostExecute - 更改公共(public)变量。在执行后

android - 使用 AsyncTask 实现 API 并将结果更新到 UI

Android 在另一个完成后立即调用 AsyncTask

对象的 add() 方法的 Java ArrayList 不起作用

java - 游程编码程序的数字在字母之前

Android : Intercept network calls (HTTP, HTTPS 等..)源 self 的应用程序内的第 3 方库

android - 在 android-16 中播放时直播音频延迟?

java.awt.geom.Point2D.createArray()

java - 通过 3g 的 ftp 客户端

android - 更新 Eclipse SDK 报错