I have a web server with a PHP script that gives me a random image stored on the server. This response is directly an image with the following header :
HTTP/1.1 200 OK
Date: Mon, 20 Jan 2020 12:10:05 GMT
Server: Apache/2.4.29 (Ubuntu)
Expires: Mon, 1 Jan 2099 00:00:00 GMT
Last-Modified: Mon, 20 Jan 2020 12:10:05 GMT
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 971646
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: image/png
As you can see, the server replies directly to me with a MIME png file type. Now I want to retrieve this image from a JAVA program. I already have a code that allows me to read text from an http request but how do I save an image from the web?
public class test {
    // one instance, reuse
    private final HttpClient httpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .build();
    public static void main(String[] args) throws Exception {
        test obj = new test();
        System.out.println("Testing 1 - Send Http POST request");
        obj.sendPost();
    }
    private void sendPost() throws Exception {
        // form parameters
        Map<Object, Object> data = new HashMap<>();
        data.put("arg", "value");
        HttpRequest request = HttpRequest.newBuilder()
                .POST(buildFormDataFromMap(data))
                .uri(URI.create("url_here"))
                .setHeader("User-Agent", "Java 11 HttpClient Bot") // add request header
                .header("Content-Type", "application/x-www-form-urlencoded")
                .build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        // print status code
        System.out.println(response.statusCode());
        // print response body
                System.out.println(response.headers());
                try {
                    saveImage(response.body(), "path/to/file.png");
                }
                catch(IOException e) {
                    e.printStackTrace();
                }
        }
    public static void saveImage(String image, String destinationFile) throws IOException {     
            //What to write here ?
    }
    private static HttpRequest.BodyPublisher buildFormDataFromMap(Map<Object, Object> data) {
        var builder = new StringBuilder();
        for (Map.Entry<Object, Object> entry : data.entrySet()) {
            if (builder.length() > 0) {
                builder.append("&");
            }
            builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
            builder.append("=");
            builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
                }
        return HttpRequest.BodyPublishers.ofString(builder.toString());
    }
Thank you for your response.
 
     
     
    