java.io.IOException: Attempted read from closed stream

☆樱花仙子☆ 提交于 2019-12-18 03:15:12

问题


I am making a HTTPPost call using Apache HTTP Client and then I am trying to create an object from the response using Jackson. Here is my code:

private static final Logger log = Logger.getLogger(ReportingAPICall.class);
ObjectMapper mapper = new ObjectMapper();

public void makePublisherApiCall(String jsonRequest)
{
    String url = ReaderUtility.readPropertyFile().getProperty("hosturl");
    DefaultHttpClient client = new DefaultHttpClient();
    try {
        HttpPost postRequest = new HttpPost(url);
        StringEntity entity = new StringEntity(jsonRequest);
        postRequest.addHeader("content-type", "application/json");
        log.info("pub id :"+ExcelReader.publisherId);
        postRequest.addHeader("accountId", ExcelReader.publisherId);
        postRequest.setEntity(entity);
        HttpResponse postResponse = client.execute(postRequest);
        log.info(EntityUtils.toString(postResponse.getEntity()));

    //  Response<PublisherReportResponse> response = mapper.readValue(postResponse.getEntity().getContent(), Response.class);
    //  log.info("Reponse "+response.toString());
    } catch (UnsupportedEncodingException ex) {
        log.error(ex.getMessage());
        log.error(ex);
        Assert.assertTrue(false, "Exception : UnsupportedEncodingException");
    } catch (ClientProtocolException ex) {
        log.error(ex.getMessage());
        log.error(ex);
        Assert.assertTrue(false, "Exception : ClientProtocolException");
    } catch (IOException ex) {
        log.error(ex.getMessage());
        log.error(ex);
        Assert.assertTrue(false, "Exception : IOException");
    }

Method makePublisherApiCall() will be called in a loop which runs for say 100 times. Basically problem occurs when I uncomment the line:

//  Response<PublisherReportResponse> response = mapper.readValue(postResponse.getEntity().getContent(), Response.class);
//  log.info("Reponse "+response.toString());

After uncommenting I am getting exception:

Attempted read from closed stream.
17:26:59,384 ERROR com.inmobi.reporting.automation.reportingmanager.ReportingAPICall - java.io.IOException: Attempted read from closed stream.

Otherwise it works fine. Could someone please let me know what I am doing wrong.


回答1:


What does EntityUtils.toString(postResponse.getEntity()) do with the response entity? I would suspect, that it is consuming the entity's content stream. The HttpClient javadoc states, that only entities, which are repeatable can be consumed more than once. Therefore if the entity is not repeatable you cannot feed the content stream to the mapper again. To avoid this you should only let the mapper consume the stream - if logging of content is required, log the parsed Response object.




回答2:


I had the same problem. Make sure you aren't consuming the entity's content stream in the "watch" or "inspect" section of your IDE. It's closed after it's consumed (read).

And sorry for my english.




回答3:


I had the same problem.

The idea is that if you consume the postResponse, then you should put it in a variable in order to use it again in different places. Else, the connection is closed and you can no longer consume the same response again.

I used to log it (for debug purposes) and always fails.




回答4:


In my case this issue was related to another reason, I am getting this issue because I haven't use

closeableresponce=client.Getmethod(FinalUrl);

In my first Test1, it was mention but when I missed out in Test2, I forget to put this code that's why stream closed message shows...

public void getapiwithheader() throws ParseException, IOException
{
    client = new RestClient();
    closeableresponce=client.Getmethod(FinalUrl);

    HashMap<String, String> headermap = new HashMap<>();
    headermap.put("content-type", "application/json");
    //****************************************************************************    
    //Status code
    //****************************************************************************      
    int statuscode =closeableresponce.getStatusLine().getStatusCode();
    System.out.println("Status code "+statuscode);
    Assert.assertEquals(statuscode,RESPONSE_STATUS_CODE_200, "Status code is not 200");


    //****************************************************************************  
    // Json String
    //****************************************************************************      
    String responsestring=  EntityUtils.toString(closeableresponce.getEntity(),"UTF-8");
    JSONObject respjsonobj = new JSONObject(responsestring);
    System.out.println("Respose Json API"+respjsonobj);

    //****************************************************************************      
    // Verify the value of the JSON
    //****************************************************************************      
    String Email =TestUtil.getValueByJPath(respjsonobj,"/email");
    System.out.println("******************************************");
    System.out.println("Print the value of Email "+Email);
    Assert.assertEquals(Email, "johndoe@google.com");
}


来源:https://stackoverflow.com/questions/18636046/java-io-ioexception-attempted-read-from-closed-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!