【问题标题】:Get content and status code from HttpResponse [duplicate]从 HttpResponse 获取内容和状态码 [重复]
【发布时间】:2013-12-31 23:53:44
【问题描述】:

我正在使用 apache 的 HttpClient(通过 Fluent API)。当我取回响应对象时,我首先会这样做:

response.returnResponse().getStatusLine().getStatusCode()

如果状态码是4xx或者5xx,我抛出异常,或者返回内容:

response.returnContent().asBytes();

这里的responseResponse 类型的对象。但是当我运行它时,我得到:

java.lang.IllegalStateException: Response content has been already consumed.

我怎样才能解决这个问题?

【问题讨论】:

  • response是什么类型?
  • responseResponse 类型,由request.execute() 返回。

标签: java apache-httpclient-4.x fluent


【解决方案1】:

Response#returnResponse()Response#returnContent() 都强制读取 HttpResponse InputStream。由于您无法读取 InputStream 两次,因此库已放置标志并检查以断言 InputStream 尚未被使用。

你无法解决这个问题。你要做的是获取底层的HttpResponse 对象并获取状态码和正文作为字节。

HttpResponse httpResponse = response.returnResponse();
httpResponse.getStatusLine().getStatusCode();
byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity());

【讨论】:

    猜你喜欢
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2011-10-28
    相关资源
    最近更新 更多