how to remove FATAL EXCEPTION: AsyncTask in android

后端 未结 1 518
悲哀的现实
悲哀的现实 2021-01-22 15:26
10-23 00:41:00.705: E/AndroidRuntime(3622): FATAL EXCEPTION: AsyncTask #1
10-23 00:41:00.705: E/AndroidRuntime(3622): java.lang.RuntimeException: An error occured while          


        
相关标签:
1条回答
  • 2021-01-22 16:16

    The reason is you can only consume Content from Entity once.

    You did it twice (maybe without you knowing it) in here

    Reader reader = new InputStreamReader(response.getEntity().getContent());
    

    and here

    response.getEntity().writeTo(out);
    

    I know this is sounds a little weird but actually the writeTo() function will get content from the entity to write to the OutputStream. You can see it in the documentation here

    Another workaround you can use is turning it to string and let GSON handle it

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                responseString = EntityUtils.toString(response.getEntity()); // content will be consume only once
                Gson gson = new Gson();
                Holder response1 = gson.fromJson(responseString, Holder.class);
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..\
            progressDialog.hide();
        } catch (IOException e) {
            //TODO Handle problems..
            progressDialog.hide();
        }
        return responseString;
    }
    

    I hope my answer can help you!

    0 讨论(0)
提交回复
热议问题