I have a rest api service which will return image as response.
Below my code
@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()));
}
I need to write a client code which will consume the above rest api to get the image, convert into blob and insert in DB.
my client code
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");
}
}
I'm not sure on how to proceed with the client code as need to read the image.
Any leads will be great
Thanks in advance
Update:
When i try to convert the inputstream to byte array using below code i get exception
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");
}
}
My Exception
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)
Any help to resolve the exception will be appreciated