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.