我正在使用Apache HTTP客户端来使用在响应中返回文件的Web服务。
我有一个发布帖子请求的方法,并返回一个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;
}
}
更新
我设法让这个工作,并了解我的资源声明尝试的行为最终关闭了连接。
这是我用来获得我所追求的结果的方法。
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);
}
我剩下的问题:
更新的实施是否安全,是否会自动释放连接?
我可以期待哪些副作用?
答案 0 :(得分:-2)
您可以使用ByteArrayInputStream
将字节数组转换回Inputstream。