1

在版本 4 中获取状态码和响应正文非常简单:

StringEntity entity = new StringEntity(jsonData.toString());
HttpResponse r = org.apache.http.client.fluent.Request.Post(uri)
        .connectTimeout(10*1000)
        .socketTimeout(10*1000)
        .addHeader("Content-Type", "application/json; charset=utf-8")
        .body(entity)
        .execute()
        .returnResponse();
int status = r.getStatusLine().getStatusCode();
String body = EntityUtils.toString(r.getEntity(), "UTF-8");
return new CoolResponse(status, body);

但是现在在 httpclient5 中,由于某种原因,无法从 HttpResponse 中获取与响应正文相关的任何内容。对此非常困惑。如果我在他们的快速入门( https://hc.apache.org/httpcomponents-client-5.0.x/quickstart.html )中遵循示例 3,它建议我创建一个 CloseableHttpClient、一个 HttpGet 和一个 CloseableHttpResponse,但这些都不允许你设置连接超时。试图找到两全其美的选择,但这里的选择似乎有点混乱。

4

1 回答 1

1

快速入门中没有提到它,但在 fluent API 中,您可以使用 handleResponse() 跟进 execute() 并将其传递给 lambda。

我最终找到了比这里的快速入门更好的文章: https ://ok2c.github.io/httpclient-migration-guide/migration-to-classic.html

于 2020-05-15T23:34:45.540 回答