【问题标题】:How can I download file with HTTPBuilder (HttpClient)?如何使用 HTTPBuilder (HttpClient) 下载文件?
【发布时间】:2012-11-28 08:26:51
【问题描述】:

我需要下载并保存文件。我正在尝试使用HTTPBuilder,因为它具有简单的 API 并且支持 cookie。我写了以下代码:

//create new httpBuilder and set cookies
def httpBuilder = ...
def file = ...  
def inputStream = httpBuilder.get(uri: urlData.url, contentType: ContentType.BINARY)
FileUtils.copyInputStreamToFile(inputStream)
  1. 如何检查文件是否正确下载(不仅仅是文件的一部分)?
  2. 对于大文件异常java.lang.OutOfMemoryError: Java heap space 发生在def inputStream = httpBuilder.get... 行我该如何解决?
  3. 通过HTTPBuilder 下载文件可能不是最佳选择。 支持 cookie 下载文件的最佳方式是什么?

【问题讨论】:

  • 我对httpbuilder了解不多,但似乎流正在加载到内存中,你能检查一下吗?
  • 是的,看起来 httpBuilder 在任何情况下都将流加载到内存中 - 如果您使用上述的 clousure api 或简单的 api。我已经用httpBuilder.client.execute 解决了

标签: groovy httpbuilder


【解决方案1】:

您是否尝试过使用自定义响应处理逻辑的 HttpBuilder GET 请求:

httpBuilder.get(uri: urlData.url, contentType: ContentType.BINARY) { 
   resp, inputStream ->
       FileUtils.copyInputStreamToFile(inputStream)
}

如果 HttpBuilder 有奇怪的问题,那么您总是可以使用经过验证的真实Apache HttpClient API,它具有完整的 cookie 支持。

HttpGet req = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(req);
// validate response code, etc.
InputStream inputStream = response.getEntity().getContent();

执行请求时可以添加localContext来管理cookies。

【讨论】:

  • 是的,我已经用HttpClient 解决了这个问题。不要使用HttpBuilder下载大文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多