使用 java11 HttpClient.sendAsync() 下载 zip 文件

Download zip file using java11 HttpClient.sendAsync()

我正在尝试使用 GitHub API 通过 java 程序下载 zip 文件。

我使用的程序如下:

public static void main(String[] args) {
        // create client
        HttpClient client = HttpClient.newHttpClient();

        // create request
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://api.github.com/repos/:owner/:repo/zipball/:ref")).build();

        // use the client to send the asynchronous request
        InputStream is = client.sendAsync(request, BodyHandlers.ofInputStream())
                .thenApply(HttpResponse::body).join();
        try {
            FileOutputStream out = new FileOutputStream("outputZipFile.zip");
            copy(is,out,1024);
            out.close();
        }catch(Exception e) {}
        
        
        
    }

    private static void copy(InputStream is, FileOutputStream out, int i) {
        // TODO Auto-generated method stub
        byte[] buf = new byte[i];
        try {
            int n = is.read(buf);
            while(n>=0) {
                out.write(buf,0,n);
                n=is.read(buf);
            }
            out.flush();
        }catch(IOException ioe) {
            System.out.println(ioe.getStackTrace());
        }
        
    }

当我尝试 运行 时,我得到空体,因此输出文件也为空。 我注意到使用 HttpURLConnection insted Java11 HttpClient 可以使它工作,但我更愿意使用此 Java11 功能来发送异步请求。

我不明白我做错了什么。

编辑:我现在使用的 HttpURLConnection 代码如下:

private void downloadVersion(String sha, String outputDestination) {
            try {
                URL url = new URL( getDownloadQuery(sha) );
                
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                if(authToken!=null) 
                    connection.setRequestProperty("Authorization", "Bearer " + authToken) ;
                connection.setRequestMethod("GET");
                
                InputStream in = connection.getInputStream();
    
                FileOutputStream out = new FileOutputStream(outputDestination);
                copy(in, out, 1024);
                out.close();
            } catch (Exception e) {}
            
        }

您的 url(当设置为更正 github 存储库时)可能会返回重定向状态 302。要使 HTTP 客户端遵循重定向,请使用 HttpClient.newBuilder() 替换 HttpClient client = HttpClient.newHttpClient() .您还可以尝试使用资源并使用 InputStream.transferTo:

来简化代码
HttpClient client = HttpClient.newBuilder().followRedirects(Redirect.ALWAYS).build();

URI uri = URI.create("https://api.github.com/repos/:owner/:repo/zipball/:ref");
HttpRequest request = HttpRequest.newBuilder().uri(uri).build();

// use the client to send the asynchronous request
InputStream is = client.sendAsync(request, BodyHandlers.ofInputStream())
        .thenApply(HttpResponse::body).join();
try (FileOutputStream out = new FileOutputStream("outputZipFile.zip")) {
    is.transferTo(out);
}