简体   繁体   中英

Download Image from Http Get Response


I'm using Postman to test an api link and my response is an image as shown below :

I have written some http get code like this to call api:

HttpClient httpClient = HttpClientBuilder.create().build();

byte[] encodedBytes = Base64.getEncoder().encode("kermit:kermit".getBytes());       
HttpGet request = new HttpGet("http://127.0.0.1:8080/activiti-rest/service/runtime/process-instances/" +processInstanceId +"/diagram");
request.setHeader("Authorization", "Basic " + encodedBytes)

request.addHeader("content-type", "image/png");

HttpResponse response = httpClient.execute(request);

Now I want to download that image to a specific path in my hard drive. I searched some post in here but it's not my expected result. Can you help me? Thank you!

First, you can't add a byte array to a String:

request.setHeader("Authorization", "Basic " + encodedBytes);

You could try something like this:

request.setHeader("Authorization", "Basic " + new String(encodedBytes, "UTF-8"));

You'll have to catch or throw the UnsupportedEncodingException .

Second, you shouldn't set the content-type header. You probably meant to use the Accept header.

Once you have the response, you can save the contents of the OutputStream to a file or do whatever you want with it.

You can try this

HttpClient httpClient = HttpClientBuilder.create().build();

HttpGet request = new HttpGet("http://127.0.0.1:8080/activiti-rest/service/runtime/process-instances/" +processInstanceId +"/diagram");

request.addHeader("content-type", "image/png");
try (CloseableHttpResponse response = client.execute(request)) {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try (FileOutputStream outstream = new FileOutputStream(new File("download-image.png"),StandardCharsets.UTF_8)) {
            entity.writeTo(outstream);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM