使用java11 httpclient.sendasync()下载zip文件

6kkfgxo0  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(313)

我正试图通过使用githubapi的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代替java11httpclient可以使它工作,但是我更喜欢使用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) {}

        }
xghobddn

xghobddn1#

您的url(设置为正确的github repos时)可能返回重定向状态302。使http客户端遵循重定向替换 HttpClient client = HttpClient.newHttpClient() 使用 HttpClient.newBuilder() . 您还可以使用try with resources和 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);
}

相关问题