Getting a release asset from GitHub returns empty response file

45 Views Asked by At

I'm trying to download an asset inside a GitHub release as a file, but the response is empty. The repository is private, but I have a working bearer token with which I can perform other calls.

static final HttpClient httpClient = HttpClient.newHttpClient();

static {
    // Edit: Turns out this doesn't make the client follow redirects
    httpClient.followRedirects();
}

static boolean downloadAsset(URI uri, Path targetPath, String bearerToken) {
    try {
        var request = HttpRequest.newBuilder(uri)
                .header("Authorization", "Bearer " + bearerToken)
                .header("Accept", "application/octet-stream")
                .build();
        var response = httpClient.send(request, HttpResponse.BodyHandlers.ofFile(targetPath));
        if (response.statusCode() == 200 || response.statusCode() == 302) {
            System.out.println("Downloaded " + uri);
            return true;
        }
        Files.deleteIfExists(targetPath);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

The api-docs say:

To download the asset's binary content, set the Accept header of the request to application/octet-stream. The API will either redirect the client to the location, or stream it directly if possible. API clients should handle both a 200 or 302 response.

The downloaded file is completely empty; What am I missing?

1

There are 1 best solutions below

0
A. M. On

Thanks to @Jorn I have checked the redirection policies. If you want to follow redirects with a HttpClient calling followRedirects() doesn't in fact make the client follow redirects, it just returns the used policy. (so it's basically a getter.)

To make a HttpClient follow redirects, you have to create it using:

HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();