2016-05-10 112 views
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); 
} 

我剩下的问题:

  1. 是更新实现安全的,不会的东西自动释放连接?

  2. 我可以期待什么副作用?

回答

-1

您可以使用ByteArrayInputStream将字节数组转换回Inputstream。

+0

这并不能解决我的实际问题。我想避免缓冲字节数组中的内容,因为这不会在大文件中扩展 – Reece

+0

由于Apache HTTP Client想要关闭到服务器的连接,因此流关闭。如果你想在RAM中保留较少的数据,你应该将数据写入文件。 – Bernard