RESTAPI读取图像并转换为BLOB

时间:2018-12-11 09:28:02

标签: java spring spring-boot jackson rest-client

我有一个rest api服务,它将返回图像作为响应。

在我的代码下面

@RequestMapping(value = "/sid/{id}", method = RequestMethod.GET,
 produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity < InputStreamResource > getImage(@PathVariable Integer id) throws IOException {
 ClassPathResource imgFile = null;
 if (id == 1) {

  imgFile = new ClassPathResource("image/sid1.jpg");
 }
 if (id == 2) {

  imgFile = new ClassPathResource("image/sid2.jpg");
 }

 return ResponseEntity
  .ok()
  .contentType(MediaType.IMAGE_JPEG)
  .body(new InputStreamResource(imgFile.getInputStream()));
}

我需要编写一个客户端代码,该代码将使用上述rest api来获取图像,转换为blob并插入DB中。

我的客户代码

public void getEntity(){
    System.out.println("Begin /GET request!");
    String getUrl = "http://localhost:8080/sid/1";
    ResponseEntity<InputStreamResource> getResponse = restTemplate.getForEntity(getUrl, InputStreamResource.class);

    if(getResponse.getBody() != null){
        ///stuck here
    }else{
        System.out.println("Response for Get Request: NULL");
    }
}

我不确定如何根据需要读取图像来处理客户端代码。

任何线索都将很棒

预先感谢

更新:

当我尝试使用以下代码将输入流转换为字节数组时,出现异常

public void getEntity() throws IllegalStateException, IOException{
    System.out.println("Begin /GET request!");
    String getUrl = "http://localhost:8080/sid/1";
    ResponseEntity<InputStreamResource> getResponse = restTemplate.getForEntity(getUrl, InputStreamResource.class);
    if(getResponse.getBody() != null){
        InputStream is=getResponse.getBody().getInputStream();
        System.out.println("Begin /GET request!"+is);
        byte[] bytes = IOUtils.toByteArray(is);
    }else{
        System.out.println("Response for Get Request: NULL");
    }
}

我的例外

Exception in thread "main" java.io.IOException: stream is closed
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.ensureOpen(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at java.io.PushbackInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2146)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:2102)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2123)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:2078)
at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:721)

任何帮助解决该异常的方法将不胜感激

0 个答案:

没有答案