0
我正在使用Apache HTTP客户端来使用返回响应中的文件的web服务。参考HTTP响应流返回对象
我有一个方法发出帖子请求并返回一个CustomServiceResult.java
,其中包含从该请求返回的文件byte[]
。
但我更愿意返回InputStream
,原因很明显。
下面的代码是我想如何实现它,目前我缓冲InputStream
并与该字节数组构造CustomServiceResult
。
返回InputStream
时,我得到的行为是流关闭,这使得总体上有意义,但并不理想。
有什么我想要做的共同模式?
我该如何坚持那InputStream
以便CustomServiceResult
的消费者可以接收文件?
public CustomServiceResult invoke(HttpEntity httpEntity) throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httppost = new HttpPost(url + MAKE_SEARCHABLE);
httppost.setEntity(httpEntity);
try (CloseableHttpResponse response = httpClient.execute(httppost)) {
HttpEntity resEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200 || resEntity.getContent() == null) {
throw new CustomServiceException(IOUtils.toString(resEntity.getContent(), "utf-8"),
statusCode);
}
// resEntity.getContent() is InputStream
return new CustomServiceResult(resEntity.getContent());
}
}
}
public class CustomServiceResult {
private InputStream objectContent;
public CustomServiceResult(InputStream objectContent) {
this.objectContent = objectContent;
}
public InputStream getObjectContent() {
return objectContent;
}
}
UPDATE
我设法得到这个工作,并了解我的尝试与资源声明最终关闭连接的行为。
这是我采取的方法来获得我后来的结果。
public CustomServiceResult invoke(HttpEntity httpEntity) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(httpEntity);
CloseableHttpResponse response = httpClient.execute(httppost);
HttpEntity resEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200 || resEntity.getContent() == null) {
throw new CustomServiceException(IOUtils.toString(resEntity.getContent(), "utf-8"),
statusCode);
}
return new CustomServiceResult(resEntity.getContent());
}
这,顺便说一句是我怎么一直在测试:
@Test
public void testCreateSearchablePdf() throws Exception {
CustomServiceResult result = client.downloadFile();
FileOutputStream os = new FileOutputStream("blabla.pdf");
IOUtils.copy(result.getObjectContent(), os);
}
我剩下的问题:
是更新实现安全的,不会的东西自动释放连接?
我可以期待什么副作用?
这并不能解决我的实际问题。我想避免缓冲字节数组中的内容,因为这不会在大文件中扩展 – Reece
由于Apache HTTP Client想要关闭到服务器的连接,因此流关闭。如果你想在RAM中保留较少的数据,你应该将数据写入文件。 – Bernard