获取响应图像为Base64

问题描述

我有一个链接,可以作为响应提供图像。

我希望使用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());不好。它只返回一堆⍁。

如何将图像获取为base64?

我尝试过

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

但结果表示图像无效。

要测试的网址:https://i.imgur.com/sIm1gSs.jpg-我遇到了这个问题。

解决方法

您需要将接收到的Stream(从HTTPClient实体类)转换为字节数组。 我对您的代码做了一些小调整,现在可以正常工作(返回图像的有效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();
        }
,

我找到了将图像获取为base64的方法:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Page Title</title>
    <meta name='viewport' content='width=device-width,initial-scale=1'>
    <style>
    @media print {
         *{visibility:hidden}
         .printable,.printable *{
            visibility:visible
         }
      }
    </style>
</head>
<body>
    <div>
        this content is not printable
    </div>
    <table class="printable">
        <tr>
            <td>
                ... table content...
            </td>
        </tr>
    </table>
    <a href="#" class="js-print-link" onclick="print()">Print</a>
</body>
</html>