java.io.IOException:尝试从关闭的流中读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18636046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.io.IOException: Attempted read from closed stream
提问by Pratik
I am making a HTTPPost call using Apache HTTP Client and then I am trying to create an object from the response using Hymanson. Here is my code:
我正在使用 Apache HTTP 客户端进行 HTTPPost 调用,然后我尝试使用 Hymanson 从响应中创建一个对象。这是我的代码:
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:
方法 makePublisherApiCall() 将在一个循环中被调用,例如 100 次。当我取消注释该行时,基本上会出现问题:
// 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.
否则它工作正常。有人可以让我知道我做错了什么。
采纳答案by Pyranja
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 javadocstates, 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.
什么是EntityUtils.toString(postResponse.getEntity())
与响应实体呢?我怀疑它正在消耗实体的内容流。该HttpClient的javadoc的状态,只有实体,这是重复的,可以多次消费。因此,如果实体不可重复,则您无法再次将内容流提供给映射器。为了避免这种情况,您应该只让映射器使用流 - 如果需要记录内容,请记录解析的 Response 对象。
回答by Rami Sharaiyri
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.
这个想法是,如果你使用 postResponse,那么你应该把它放在一个变量中,以便在不同的地方再次使用它。否则,连接将关闭,您不能再使用相同的响应。
I used to log it (for debug purposes) and always fails.
我曾经记录它(用于调试目的)并且总是失败。
回答by august0490
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).
我有同样的问题。确保您没有在 IDE 的“观察”或“检查”部分使用实体的内容流。它在消耗(读取)后关闭。
And sorry for my english.
对不起我的英语。
回答by lokesh sharma
In my case this issue was related to another reason, I am getting this issue because I haven't use
在我的情况下,这个问题与另一个原因有关,我遇到这个问题是因为我没有使用
closeableresponce=client.Getmethod(FinalUrl);
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...
在我的第一个 Test1 中,它被提及但是当我在 Test2 中错过时,我忘记放置此代码,这就是为什么流关闭消息显示...
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, "[email protected]");
}