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

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.
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.

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.

Related

POST in JAVA using HttpURLConnection getting a HTTP response code 400

I'm pretty new to making HTTP connections and working with API's in Java, so I'm not sure where the problem lies. When I send out a POST connection request in order to send a JSON formatted String of text to the other side, I get an error back along with a 400 response code. When I look up that code, it seems my connection isn't properly formatted. Code is below, along with the error message. Please help! Thanks!
public void sendToAPI(String urlPass, String param) throws IOException {
URL url = new URL(urlPass);
HttpURLConnection connectionOut = (HttpURLConnection) url.openConnection();
connectionOut.setRequestMethod("POST");
connectionOut.setConnectTimeout(5000);
connectionOut.setReadTimeout(5000);
connectionOut.setRequestProperty("Content-Type", "application/json");
connectionOut.setRequestProperty("Content-Length", Integer.toString(param.length()));
connectionOut.setDoOutput(true);
connectionOut.setDoInput(true);
connectionOut.connect();
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
stream.flush();
stream.close();
int responsecode = connectionOut.getResponseCode();
if(responsecode != 200) {
System.out.println("Response Code is " + responsecode);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connectionOut.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
//printing result from response
System.out.println(response.toString());
}
Response Code is 400
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL:XXX
u can try this code:
InputStream inputStream;
if (responseCode == 200) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String lines;
while ((lines = reader.readLine()) != null) {
builder.append(lines);
builder.append(System.getProperty("line.separator"));
}
String retStr = builder.toString().trim();
reader.close();
System.out.println("retStr: " + retStr);
So after playing around with the DataOutputStream, I replaced the below code:
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
With another example I found online:
OutputStream os = connectionOut.getOutputStream();
os.write(param.getBytes());
os.flush();
os.close();
I'm not sure yet why, but this suddenly got the proper response code I was looking for, so the format it was sent in matched what they requested. Thanks for all responses.

How i can get connected with qc 12 with rest api

Can u please help me to understand with simple piece of java code to get connect wth qc 12 using rest api.
I gone thorough the rest api documentation but am not clear with how to start with.but it will be helpful if people can show me a simple java code for authentication(login,logout or getting defect details) using rest api. Also want to know do i need to include any jars in my build path.
Thanks a lot friends.
I don't quite get what you're asking, but if you want to connect to a REST API, there are several ways... I usually use HttpURLConnection, here's an example of a get:
public String getProfile(String URL) throws IOException {
URL getURL = new URL(url);
//Establish a https connection with that URL.
HttpURLConnection con = (HttpURLConnection) getURL.openConnection();
//Select the request method, in this case GET.
con.setRequestMethod("GET");
//Add the request headers.
con.setRequestProperty("header", headerValue);
System.out.println("\nSending 'GET' request to URL : " + url);
int responseCode;
try {
responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
System.out.println("Error: Connection problem.");
}
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
//Save the response.
response.append(inputLine + '\n');
}
br.close();
return response.toString();
}

Cannot get a fully JSON using jersey

I'm trying to read a json by using jersey api. That's a long json.
The problem is I can't get the full json. Please look at both links below for more understanding.
Expect result. (10 objects)
Actual result (Sorry because this one can't be format. But it can only get 4 objects and a bit of the 5th object.)
This is my code to get json:
Client client = Client.create();
WebResource resource = client.resource(url);
ClientResponse clientResponse = resource.accept("application/json").get(ClientResponse.class);
if(clientResponse.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + clientResponse.getStatus());
}
String output = "";
String response = "";
BufferedReader br = new BufferedReader(new InputStreamReader(
(clientResponse.getEntityInputStream())));
while ((output = br.readLine()) != null) {
response = response + output;
}
br.close();
return response;
I don't know what I did wrong here.
Your client is receiving the full output. You are seeing the truncated output in the log because the LoggingFilter that you have enabled by default will truncate the output.
Check the constructors here for how to set the maxEntitySize.
https://jersey.java.net/apidocs/2.11/jersey/org/glassfish/jersey/filter/LoggingFilter.html

Imgur API request using Java returns 400 status

I am trying to send a GET request to the Imgur API to upload an image.
When I use the following code I receive a 400 status response from the Imgur server - which, according to the Imgur error documentation, means I am missing or have incorrect parameters.
I know the parameters are correct as I have tested them directly in the browser URL (which successfully uploads an image) - so I must not be adding the parameters correctly within the code:
private void addImage(){
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode("http://www.lefthandedtoons.com/toons/justin_pooling.gif", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("myPublicConsumerKey", "UTF-8");
// Send data
java.net.URL url = new java.net.URL("http://api.imgur.com/2/upload.json");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Logger.info( line );
}
wr.close();
rd.close();
}
This code is based on the API examples provided by Imgur.
Can anyone tell me what I am doing wrong and how I may resolve the problem?
Thanks.
In this sample, imgur service returns 400 Bad Request status response with a non-empty body because of incorrect API key. In case of non successful HTTP response you shold read the response body from an error input stream. For example:
// Get the response
InputStream is;
if (((HttpURLConnection) conn).getResponseCode() == 400)
is = ((HttpURLConnection) conn).getErrorStream();
else
is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
And, by the way your example is POST, not GET, because you are sending the parameters in the request body instead of the URL.

java inputstream print to console the content

sock = new Socket("www.google.com", 80);
out = new BufferedOutputStream(sock.getOutputStream());
in = new BufferedInputStream(sock.getInputStream());
When i try to do printing out of content inside "in" like below
BufferedInputStream bin = new BufferedInputStream(in);
int b;
while ( ( b = bin.read() ) != -1 )
{
char c = (char)b;
System.err.print(""+(char)b); //This prints out content that is unreadable.
//Isn't it supposed to print out html tag?
}
If you want to print the content of a web page, you need to work with the HTTP protocol. You do not have to implement it yourself, the best way is to use existing implementations such as the java API HttpURLConnection or Apache's HttpClient
Here is an example of how to do it with HttpURLConnection:
URL url = new URL("http","www.google.com");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setAllowUserInteraction( false );
urlc.setDoInput( true );
urlc.setDoOutput( false );
urlc.setUseCaches( true );
urlc.setRequestMethod("GET");
urlc.connect();
// check you have received an status code 200 to indicate OK
// get the encoding from the Content-Type header
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}
// close sockets, handle errors, etc.
As written above, you can save traffic by adding the Accept-Encoding header and check the
Content-Encoding header of the response.
Here is an HttpClient Example, taken from here:
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
Very easy to create a String from a Stream using Java 8 Stream API:
new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"))
Using IntelliJ I even can set this beeing a debug expression:
I guess in Eclipse it will work similar.
If you what to fetch the content of a webpage, you should take a look at apache httpclient instead of coding this yourself, expect for learning purposes or any other really good reason.

Categories