shuang shuang - 7 months ago 32
Java Question

How to binary data from a get response using jersey client?

I am trying to make a rest Get call using jersey client. Base on the api docs, the request returns an image as binary data. When I make the rest Get call using postman, I can the actual image back (im asumming postman converts the binary back to image/png). This is the following headers that is returned from postman.

enter image description here

I try making the rest Get using jersey client in java. Here is my code:

private Client client = ClientBuilder.newClient( new ClientConfig().register(LoggingFilter.class).register(MultiPartFeature.class));
private WebTarget myServer;

myServer= client.target(baseURL);

public void restGetImage(String requestURL, String headers) {

BufferedReader br = null;
StringBuilder sb = new StringBuilder();

String line;

MultivaluedMap<String, Object> userHeaders = storeHeadersInMap(headers);

WebTarget target = getWebTarget().path(requestURL);

Response response = target.request(MediaType.APPLICATION_OCTET_STREAM)
.headers(userHeaders)
.get();

System.out.println("Reuqest URL: " + session.get("baseurl") + requestURL);
int responseCode = response.getStatus();
InputStream inputStream = response.readEntity(InputStream.class);

String contentType = response.getHeaderString("Content-Type");

// br = new BufferedReader(new InputStreamReader(inputStream));
//
// try {
// while((line = br.readLine()) != null) {
// sb.append(line);
// }
//
// br.close(); //close buffered reader
//
// } catch (IOException e) {
// e.printStackTrace();
//
// }
//
// RestResponse data = new RestResponse(responseCode, sb.toString(), contentType);
// data.setResponseHeader(response.getHeaders());
//
// System.out.println("response code: " + responseCode);
// System.out.println("response Content-Type: " + contentType);
// System.out.println("Response body: " + sb.toString());

// return data;
}


Please excuse all the comments because I am still testing the code. Basically the code returns 200 response status, but when it fails to read the response. It throws an exception at InputStream inputStream = response.readEntity(InputStrean.class).

Apr 22, 2016 11:37:29 AM
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderIn
terceptor aroundReadFrom
SEVERE: MessageBodyReader not found for media type=image/png, type=class
com.itextpdf.text.pdf.codec.Base64$InputStream, genericType=class
com.itextpdf.text.pdf.codec.Base64$InputStream.


My goal is to be able to read the binary response data. Any insight is apprectiated. Thanks.

Answer

SEVERE: MessageBodyReader not found for media type=image/png, type=class
com.itextpdf.text.pdf.codec.Base64$InputStream, genericType=class
com.itextpdf.text.pdf.codec.Base64$InputStream.

You're using the wrong InputStream class. You should be using java.io.InputStream. Check and fix your import.