As we saw in the Setting a request body and Handling response body types sections, the HTTP Client API can send and receive text and binary data (for example, images, videos, and so on).
Downloading a file relies on the following two coordinates:
- Sending a GET request
- Handling the received bytes (for example, via BodyHandlers.ofFile())
The following code downloads hibernate-core-5.4.2.Final.jar from the Maven repository in the project classpath:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://.../hibernate-core-5.4.2.Final.jar"))
.build();
HttpResponse<Path> response
= client.send(request, HttpResponse.BodyHandlers.ofFile(
Path.of("hibernate-core-5.4.2.Final.jar")));
If the resource to download is delivered via the Content-Disposition HTTP header, which is of the Content-Disposition attachment; filename="..." type, then we can rely on BodyHandlers.ofFileDownload(), as in the following example:
import static java.nio.file.StandardOpenOption.CREATE;
...
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://...downloadfile.php
?file=Hello.txt&cd=attachment+filename"))
.build();
HttpResponse<Path> response = client.send(request,
HttpResponse.BodyHandlers.ofFileDownload(Path.of(
System.getProperty("user.dir")), CREATE));
More files that can be tested are available here: http://demo.borland.com/testsite/download_testpage.php.