有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何使用Java下载GET https请求的zip格式响应文件。在《邮差》中,回应是一些垃圾角色

我正在为此使用Java创建连接HttpURLConnection,但不确定如何下载响应

当我从response中检查标题字段时,下面是我找到的详细信息

{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]}>

在上面的对象(higlight)中,内容配置中有一个文件名,我应该能够将该文件名自动下载到本地文件夹或路径

有人能帮忙吗


共 (3) 个答案

  1. # 1 楼答案

    要使用HttpURLConnection下载,请使用

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

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

  2. # 2 楼答案

    您可以使用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();
    
    // Print in console
    Scanner sc = new Scanner(zis);
    while (sc.hasNextLine()) {
        System.out.println(sc.nextLine());
    }
    
  3. # 3 楼答案

    如果您使用的是Java11或更高版本,则根本不需要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("\"")) {
                // filename is everything inside double-quotes.
                int endIndex = filename.indexOf('"', 1);
                filename = filename.substring(1, endIndex);
            } else {
                // filename is unquoted and goes until ';' or end of string.
                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);
    }