获取响应图像作为 Base64

Get response image as Base64

我有一个 link,它给出了一张图片作为响应。

我想使用 apache-httpclient 将此图像作为 base64 格式。

这是我写的:

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();
}

这个EntityUtils.toString(httpResponse.getEntity());不好。它returns只是一堆⍁.

如何获取 base64 格式的图像?

我试过了

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

但结果表示无效图像。

URL 用于测试:https://i.imgur.com/sIm1gSs.jpg - 这个我有问题。

我找到了获取 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);

您需要将接收到的流(来自 HTTPClient 实体 class)转换为字节数组。 我对你的代码做了一些小的调整,现在它工作正常(returns 图像的有效 base64 表示)

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();
        }