org.apache.http.ConnectionClosedException:块编码消息正文的过早结尾:需要关闭块

pjngdqdw  于 2023-05-01  发布在  Apache
关注(0)|答案(2)|浏览(694)

我正在试用RestAssured并写了以下声明-

String URL = "http://XXXXXXXX";
Response result = given().
            header("Authorization","Basic xxxx").
            contentType("application/json").
            when().
            get(url);
JsonPath jp = new JsonPath(result.asString());

在最后一个语句中,我收到以下异常:
org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
在我的响应中返回的头是:
Content-Type → application/json; qs=1 Date → Tue, 10 Nov 2015 02:58:47 GMT Transfer-Encoding → chunked
谁能指导我解决这个异常,并指出我是否遗漏了任何东西或任何不正确的实现。

4ktjp1zp

4ktjp1zp1#

我有一个与rest-assured无关的类似问题,但这是Google发现的第一个结果,所以我在这里发布我的答案,以防其他人面临同样的问题。
对我来说,问题是(正如ConnectionClosedException明确指出的那样)closing在阅读响应之前的连接。沿着如下的东西:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);

try {
    doSomthing();
} finally {
    response.close();
}
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent(); // Response already closed. This won't work!

修复是显而易见的。排列代码,使响应在关闭后不被使用:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget);

try {
    doSomthing();
    HttpEntity entity = response.getEntity();
    InputStream instream = entity.getContent(); // OK
} finally {
    response.close();
}
xpszyzbs

xpszyzbs2#

也许你可以尝试摆弄连接配置?例如:

given().config(RestAssured.config().connectionConfig(connectionConfig().closeIdleConnectionsAfterEachResponse())). ..

相关问题