How to download the response file which is in zip format for a GET https request using Java. In postman the response is some junk character

huangapple go评论73阅读模式
英文:

How to download the response file which is in zip format for a GET https request using Java. In postman the response is some junk character

问题

我正在使用Java来创建一个连接HttpURLConnection,但不太清楚如何下载响应。

当我检查响应的标头字段时,我找到了以下详细信息:

> {null=[HTTP/1.1 200 OK], Server=[Apigee LB], Access-Control-Allow-Origin=[*], Access-Control-Allow-Methods=[GET、PUT、POST、DELETE], Content-Disposition=[attachment; filename="OfflineQueryResult-2ba8631e-c542-49f0-9012-32875875d5f8.zip"], Connection=[keep-alive]、Content-Length=[265]、Access-Control-Max-Age=[3628800]、Date=[Sun, 23 Aug 2020 10:15:42 GMT]、Access-Control-Allow-Headers=[origin、x-requested-with、accept]、Content-Type=[text/xml]}>

在上述对象中(已高亮显示),在Content-Disposition中有一个文件名,我应该能够自动下载该文件名到本地文件夹或路径。

有人能帮忙吗?

英文:

I am using Java for this to create a connection HttpURLConnection but not sure how to download the response.

When I checked for the header fields from response, below are the details I found

> {null=[HTTP/1.1 200 OK], Server=[Apigee LB], Access-Control-Allow-Origin=[*], Access-Control-Allow-Methods=[GET, PUT, POST, DELETE], Content-Disposition=[attachment; filename="OfflineQueryResult-2ba8631e-c542-49f0-9012-32875875d5f8.zip"], Connection=[keep-alive], Content-Length=[265], Access-Control-Max-Age=[3628800], Date=[Sun, 23 Aug 2020 10:15:42 GMT], Access-Control-Allow-Headers=[origin, x-requested-with, accept], Content-Type=[text/xml]}>

Here in the above object (higlighted), there is a filename inside the Content-Disposition, that filename I should be able to download automatically to the local folder or path

Can someone please help here

答案1

得分: 1

如果您使用的是Java 11或更高版本,则根本不需要使用HttpURLConnection。您可以使用java.net.http包:

URL url = /* ... */;

Path downloadDir = Path.of(System.getProperty("user.home"), "Downloads");

HttpResponse<Path> response = HttpClient.newHttpClient().send(
    HttpRequest.newBuilder(url.toURI()).GET().build(),
    HttpResponse.BodyHandlers.ofFileDownload(downloadDir));

Path downloadedFile = response.body();

如果您使用的是早于Java 11的版本,可以使用getHeaderField方法获取内容的Disposition头。您可以使用Files.copy进行下载。

HttpURLConnection conn = /* ... */;

Path downloadDir = Paths.get(System.getProperty("user.home"), "Downloads");

Path downloadedFile = null;
String disposition = conn.getHeaderField("Content-Disposition");
if (disposition != null) {
    String filenameIndex = disposition.indexOf("filename=");
    if (filenameIndex >= 0) {
        String filename = disposition.substring(filenameIndex + 9);
        if (filename.startsWith("\"")) {
            int endIndex = filename.indexOf('"', 1);
            filename = filename.substring(1, endIndex);
        } else {
            int endIndex = filename.indexOf(';');
            if (endIndex > 0) {
                filename = filename.substring(0, endIndex);
            }
        }
        downloadedFile = downloadDir.resolve(filename);
    }
}
if (downloadedFile == null) {
    downloadedFile = Files.createTempFile(downloadDir, null, null);
}

try (InputStream urlStream = conn.getInputStream()) {
    Files.copy(urlStream, downloadedFile,
        StandardCopyOption.REPLACE_EXISTING);
}
英文:

If you’re using Java 11 or later, you don’t need HttpURLConnection at all. You can use the java.net.http package:

URL url = /* ... */;

Path downloadDir = Path.of(System.getProperty(&quot;user.home&quot;), &quot;Downloads&quot;);

HttpResponse&lt;Path&gt; response = HttpClient.newHttpClient().send(
    HttpRequest.newBuilder(url.toURI()).GET().build(),
    HttpResponse.BodyHandlers.ofFileDownload(downloadDir));

Path downloadedFile = response.body();

If you’re using a version of Java older than 11, you can obtain the disposition header using the getHeaderField method. And you can download using Files.copy.

HttpURLConnection conn = /* ... */;

Path downloadDir = Paths.get(System.getProperty(&quot;user.home&quot;), &quot;Downloads&quot;);

Path downloadedFile = null;
String disposition = conn.getHeaderField(&quot;Content-Disposition&quot;);
if (disposition != null) {
    String filenameIndex = disposition.indexOf(&quot;filename=&quot;);
    if (filenameIndex &gt;= 0) {
        String filename = disposition.substring(filenameIndex + 9);
        if (filename.startsWith(&quot;\&quot;&quot;)) {
            // filename is everything inside double-quotes.
            int endIndex = filename.indexOf(&#39;&quot;&#39;, 1);
            filename = filename.substring(1, endIndex);
        } else {
            // filename is unquoted and goes until &#39;;&#39; or end of string.
            int endIndex = filename.indexOf(&#39;;&#39;);
            if (endIndex &gt; 0 ) {
                filename = filename.substring(0, endIndex);
            }
        }
        downloadedFile = downloadDir.resolve(filename);
    }
}
if (downloadedFile == null) {
    downloadedFile = Files.createTempFile(downloadDir, null, null);
}

try (InputStream urlStream = conn.getInputStream()) {
    Files.copy(urlStream, downloadedFile,
        StandardCopyOption.REPLACE_EXISTING);
}

答案2

得分: 0

你可以使用 JAX-RS 客户端 API 来消费 ZIP 响应:

Client client = ClientBuilder.newClient();
InputStream is = client.target("http://host:port")
                       .path("api").path("API-Path")
                       .request().accept("application/zip")
                       .get(InputStream.class);

ZipInputStream zis = new ZipInputStream(is);
zis.getNextEntry();

// 在控制台打印
Scanner sc = new Scanner(zis);
while (sc.hasNextLine()) {
    System.out.println(sc.nextLine());
}
英文:

You can use JAX-RS Client API to consume the ZIP response :

Client client = ClientBuilder.newClient();
InputStream is = client.target(&quot;http://host:port&quot;)
                       .path(&quot;api&quot;).path(&quot;API-Path&quot;)
                       .request().accept(&quot;application/zip&quot;)
                       .get(InputStream.class);

ZipInputStream zis = new ZipInputStream(is);
zis.getNextEntry();

// Print in console
Scanner sc = new Scanner(zis);
while (sc.hasNextLine()) {
    System.out.println(sc.nextLine());
}

答案3

得分: 0

使用HttpURLConnection进行下载时,你可以这样做:

HttpURLConnection myConnection = ...;
InputStream stream = myConnection.getInputStream();

然后你需要从流中读取所有的字节。基本上,你创建一个读取缓冲区(字节),在InputStream上调用read(byte[]),然后将这些字节转储到一个较大的缓冲区中,可能是一个ByteBuffer对象,直到没有更多内容可读(read返回-1)。另外,你可以插入DataFetcher来为你执行上述操作。

英文:

To download using HttpURLConnection, you use

HttpURLConnection myConnection = ...;
InputStream stream = myConnection.getInputStream();

Then you need to suck up all the bytes from the stream. Basically, you create a read buffer (byte), call read(byte[]) on the InputStream, and then dump those bytes into a larger buffer, possibly a ByteBuffer object, until there is nothing left to read (read returns -1). Also, you can plug in DataFetcher to do the above for you

huangapple
  • 本文由 发表于 2020年8月25日 22:40:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63581306.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定