0

I have a link which gives as response an image.

I want, with apache-httpclient, to get this image as base64.

This is what I wrote:

try(CloseableHttpClient httpClient = HttpClients.createDefault()){

    HttpGet httpGet = new HttpGet("...");

    try(CloseableHttpResponse httpResponse = httpClient.execute(httpGet)){

        int code = httpResponse.getStatusLine().getStatusCode();
        String body = EntityUtils.toString(httpResponse.getEntity());

        if(code == HttpStatus.SC_OK){

            System.out.print(body); //returns weird chars ⍁
            return;

        }

        String reason = httpResponse.getStatusLine().getReasonPhrase();
        throw new Exception("Error - code: " + code + " - reason: " + reason + " - body: " + body);

    }

}catch (Exception e){
    e.printStackTrace();
}

This EntityUtils.toString(httpResponse.getEntity()); is not good. It returns just a bunch of ⍁.

How I can get the image as base64?

I tried

Base64.getEncoder().encodeToString(EntityUtils.toString(httpResponse.getEntity()).getBytes());

but the result represent an invalid image.

URL for test: https://i.stack.imgur.com/jRsnt.jpg - with this one I have problems.

KunLun
  • 3,109
  • 3
  • 18
  • 65
  • Does this answer your question? [Get image from http GET response as base64 String](https://stackoverflow.com/questions/25883180/get-image-from-http-get-response-as-base64-string) – Joe Oct 04 '20 at 12:04
  • This is not `apache-httpclient` specific. See [this](https://stackoverflow.com/questions/13109588/encoding-as-base64-in-java) StackOverflow post on how to Base64 encode the result of `EntityUtils.toString(...)`. – concision Oct 04 '20 at 12:06
  • @concision, `Base64.getEncoder().encodeToString( EntityUtils.toString( httpResponse.getEntity() ).getBytes() );` - gives me an invalid image. I tried to compute the image based on what returns, but is an invalid image. – KunLun Oct 04 '20 at 12:14
  • @Abra, I added an url from imgur. I have the same problem. – KunLun Oct 04 '20 at 12:21
  • You are not supposed to convert it to string. You are supposed to read the bytes of the response and convert them to base64. – RealSkeptic Oct 04 '20 at 12:41

2 Answers2

1

You need to convert received Stream (from HTTPClient entity class) to byte array. I made some minor tweaks to your code and it works fine now (returns a valid base64 representation of image)

try(CloseableHttpClient httpClient = HttpClients.createDefault()){

            HttpGet httpGet = new HttpGet("https://i.imgur.com/sIm1gSs.jpg");

            try(CloseableHttpResponse httpResponse = httpClient.execute(httpGet)){

                int code = httpResponse.getStatusLine().getStatusCode();
                
                // You are getting stream from httpclient. It needs to be converted to byte array
                // We will use byteArrayOutputStream. 
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                httpResponse.getEntity().writeTo(byteArrayOutputStream);    // Writing to ByteArrayStream

                String body = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());

                if(code == HttpStatus.SC_OK){

                    System.out.print(body); //returns valid Base64 image
                    return;

                }

                String reason = httpResponse.getStatusLine().getReasonPhrase();
                throw new Exception("Error - code: " + code + " - reason: " + reason + " - body: " + body);

            }

        }catch (Exception e){
            e.printStackTrace();
        }
Ashish Gupta
  • 112
  • 6
0

I found the way to get the image as base64:

BufferedImage bufferedImage = ImageIO.read(httpResponse.getEntity().getContent());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
String body = Base64.getEncoder().encodeToString(imageInByte);
KunLun
  • 3,109
  • 3
  • 18
  • 65