java程序员封闭,java.io.IOException:尝试从封闭流中读取

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 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 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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值