从Http下载图像获取响应

时间:2019-02-19 03:21:30

标签: java rest


我正在使用Postman测试api链接,我的响应如下图所示:

我已经写了一些http get代码来调用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);

现在,我想将该图像下载到硬盘驱动器中的特定路径。我在这里搜索了一些帖子,但这不是我的预期结果。 你能帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:1)

首先,您不能将字节数组添加到字符串:

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

您可以尝试这样的事情:

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

您必须赶上或扔下UnsupportedEncodingException

第二,您不应该设置content-type标头。您可能打算使用Accept标头。

收到回复后,您可以将OutputStream的内容保存到文件中,或使用它进行任何操作。

答案 1 :(得分:0)

您可以尝试

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