I want to convert Response to string
Response response = ClientBuilder.newBuilder().sslContext(sslContext).build().target(url)
.request(MediaType.APPLICATION_JSON).get();
// I have tried as below.. It didn't work
String result = (String)response.getEntity();
Error is java.lang.ClassCastException: org.glassfish.jersey.client.HttpUrlConnector$1 cannot be cast to java.lang.String
Please not i am using Java 1.6 version and i cannot find methods like readEntity(String.class) and getEntity(String.class) from Response class.
Alternate way works as below by giving String.class in get. But i need Response object First to check the status code then i want to convert it to String.
String response = ClientBuilder.newBuilder().sslContext(sslContext).build().target(url)
.request(MediaType.APPLICATION_JSON).get(String.class);
Please assist in solving this
If we don't use Jersey client jar, then we don't get readEntity(class) and getEntity(class). These methods are not part of javax.ws.rs.core.Response they are part of Jersey clientjar. So if we are using javax.ws.rs.core.Response, then we have to manually convert as below
javax.ws.rs.core.Response response;
String result = readInputStreamAsString((InputStream) response.getEntity());
public static String readInputStreamAsString(InputStream in) {
try {
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while (result != -1) {
byte b = (byte) result;
buf.write(b);
result = bis.read();
}
return buf.toString();
} catch (IOException ex) {
return null;
}
}