从HttpClient 3转换为4
我设法对以下所有内容进行了更改:
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()。
InputStream rstream; try { HttpResponse response = client.execute(HttpHost, method); rstream = response.getEntity().getContent(); } catch (IOException e) { return BadSpot(e.getMessage()); }
上面应该做你要问的。
HttpResponse.getEntity() ,后跟HttpEntity.getContent()
util类有一些有用的方法:
EntityUtils.toString(response.getEntity());
在apache的网站上的例子中也有一些有用的东西
使用EntityUtils
并在使用实体之前检查返回的实体是否为not 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,并且最重要的是您必须确保在实际关闭响应/释放连接之前消耗它。