2016-05-10 113 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