从 HttpClient 3 转换为 4

发布于 2024-10-10 05:33:52 字数 347 浏览 3 评论 0原文

我已经设法对除以下内容之外的所有内容进行更改:

HttpClient client;
HttpPost method;   
client = new DefaultHttpClient();
method = new HttpPost(url); 

InputStream rstream;
try {
    rstream = method.getResponseBodyAsStream();
} catch (IOException e) {
    return BadSpot(e.getMessage()); 
}

我不确定应该用什么替换 getResponseBodyAsStream() 。

I've managed to make changes to everything but the following:

HttpClient client;
HttpPost method;   
client = new DefaultHttpClient();
method = new HttpPost(url); 

InputStream rstream;
try {
    rstream = method.getResponseBodyAsStream();
} catch (IOException e) {
    return BadSpot(e.getMessage()); 
}

What I'm not sure of is what I should replace getResponseBodyAsStream() with.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

め可乐爱微笑 2024-10-17 05:33:52
InputStream rstream;
try {
    HttpResponse response = client.execute(HttpHost, method);
    rstream = response.getEntity().getContent();
} catch (IOException e) {
    return BadSpot(e.getMessage()); 
}

上面应该做你所要求的。

InputStream rstream;
try {
    HttpResponse response = client.execute(HttpHost, method);
    rstream = response.getEntity().getContent();
} catch (IOException e) {
    return BadSpot(e.getMessage()); 
}

above should do what you are asking.

左岸枫 2024-10-17 05:33:52

util 类有一些有用的方法:

EntityUtils.toString(response.getEntity());

apache 的示例中也有一些有用的内容网站

The util class has some helpful methods:

EntityUtils.toString(response.getEntity());

There is also some useful stuff in the examples at apache's website

梨涡少年 2024-10-17 05:33:52

使用 EntityUtils 并在使用实体之前检查返回的实体是否为 null:

InputStream rstream;
try {
    HttpResponse response = client.execute(HttpHost, method);

    rstream = Optional.ofNullable(httpResponse.getEntity())
    .map(e -> response.getContent()).orElse(null);

} catch (IOException e) {
    return BadSpot(e.getMessage()); 
}

注意:此处的 InputStream 可以为 null,最重要的是必须确保在实际关闭响应/释放连接之前它已被消耗。

Use EntityUtils and check the returned entity to be not null before consuming the entity:

InputStream rstream;
try {
    HttpResponse response = client.execute(HttpHost, method);

    rstream = Optional.ofNullable(httpResponse.getEntity())
    .map(e -> response.getContent()).orElse(null);

} catch (IOException e) {
    return BadSpot(e.getMessage()); 
}

NOTE: the InputStream here can be null and most of all you have to ensure that it's consumed before you actually close the response/release the connection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文