Response codes from Java.net.Url conection - Rest Webservice Client - java

I am using Java.Net.URL for making a Rest webservice call.
using the below example code.
URL url = new URL("UrlToConnect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
i am trying to capture response code from this webservice call. I observed that Even after putting a wrong URL i am getting 200 response code from the connection. Please suggest a way by which i can capture response codes 200 , 201 and 202.
Thanks.

Related

Http 401 error when posting to GoogleGroups API in Java?

The documentation on the Google API site does not include any complete working examples on using the groups api to access or modify a group, such as adding a member. There are snippets for different parts, but I am getting a 401 error when I put it all together and I have no idea if I am leaving out some key part.
I have tried putting the snippets I have found together into a working application, but am getting a 401 error.
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream("<path to my json file I downloaded from the service accounts page>"))
.createScoped(Collections.singleton("https://www.googleapis.com/auth/admin.directory.group"));
URL url = new URL("https://www.googleapis.com/admin/directory/v1/groups/<identifier to the group, such as the group email address>/members");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + credential.getAccessToken());
conn.setRequestProperty("Accept", "application/json");
StringBuffer jsonParamsBuffer = new StringBuffer();
jsonParamsBuffer .append("{")
.append("\"email\": \"")
.append("test-email#notarealdomain.fake")
.append("\", ")
.append("\"role\": \"")
.append("MEMBER")
.append("\"")
.append("}")
.append("]")
.append("}");
OutputStream os = conn.getOutputStream();
os.write(jsonParamsBuffer.toString().getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Response from Google Groups APi:");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
Server returned HTTP response code: 401 for URL: https://www.googleapis.com/admin/directory/v1/groups//members

java.io.EOFException: Response had end of stream after 0 bytes

I am trying to call a web service using a java code which is throwing java.io.EOFException: Response had end of stream after 0 bytes for the large chunk of data.
The same web service call works in Postman REST Client, but Java code throws an error and it is not able to fetch web service response.
Can someone please help me with this?
Below is the code snippet for reference:
String output;
URL url = new URL(wsUrl); //wsUrl is a web service URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String authorization = "**************" + ":" + "*********";
String basicAuth = "Basic " + java.util
.Base64
.getEncoder()
.encodeToString(authorization.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
System.out.println("Output from Server .... \n");
String jsonstring = new String();
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();

Receiving encoded response to HttpsURLConnection GET request

I am working on an Android app which will connect to a webpage using the java class HttpsURLConnection and parse the HTML response using JSoup. The issue is that the HTML response from the website appears to be encoded. Any ideas on what I can do to get the actual HTML?
Here is my code for contacting the website:
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8,en-GB;q=0.6");
conn.setRequestProperty("Accept-Encoding" , "gzip, deflate, sdch");
conn.setRequestProperty("Connection" , "keep-alive");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
Log.v(TAG,"\nSending 'GET' request to URL : " + url);
Log.v(TAG,"Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
And a snippet of the response:
��������������]�r�6��۞�w#ՙ�NDQ�ﱥ|�siv�Kkw�m&�HH�M, Z��ff_c_o�d�#���9�l�6����� �_=w|����/A{��!W� LZ��������f]�=wc߽�2,˨�|�8x��~�}�x1�$Ib�Uq�7�j�X|;��K
EDIT: The HTML was encoded with GZIP, as shown in the request headers here.
The solution to this issue was to use the GZIPInputStream class as shown below:
BufferedReader in = new BufferedReader(new InputStreamReader(
new GZIPInputStream(conn.getInputStream())));
Based on the headers returned with the request, we can conclude that the content is encoded using gzip. Luckily, there is an easy method to decode a gzip encoding stream, using the GZIPInputStream class.
Don't know which URL you are trying to access, but have you tried setting the charset ?
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF8"));

IBM Watson Q and A API gives 500 response code

I have written a Java Code to test the Watson Question and Answers API. However, I'm getting response code 500, when I run it. I have checked the api url and my login credentials. The problem seems to be somewhere else. Any hints or debugging suggestions would be of great help.
String url = "https://watson-wdc01.ihost.com/instance/526/deepqa/v1/question";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String userCredentials = "username:password";
String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestProperty("X-SyncTimeout", "30");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestMethod("POST");
String query = "{\"question\": {\"questionText\": \"" + "What are the common respiratory diseases?" + "\"}}";
System.out.println(query);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
When i open the same url with the browser I get this:
Watson Error!!
Error Encountered!!
Unable to communicate with Watson.
Whats wrong? Could it be something with the configuration? Or is the server down?
Any hints or debugging suggestions would be of great help.
Attempt the same request using your web browser ... or the curl utility.
Capture and output the contents of the error stream.
I don't think that this is the cause of your problems, but it is wrong anyway:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(query);
wr.flush();
You are writing to an API that expects text (JSON). You should therefore use a Writer, not a data (binary) output stream:
Writer wr = new OutputStreamWriter(con.getOutputStream(), "LATIN-1");
wr.write(query);
wr.flush();

How to read restful response on client side in java for post

I have returning response to client as
return Response.status(200).entity("Data was succesfully loaded into database").build();
I have to read this on client my client code
URL url=new URL(urlString);
// URLConnection connection=url.openConnection();
//connection.setDoOutput(true);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/json");
how to read these type of responses on client side
Once you have HttpURLConnection you can send data to the server (if this is needed, but looks like as it is, because you have POST request):
DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
wr.writeBytes(yourData);
wr.flush();
wr.close();
Then you can check for response code (for e.g. if it is 200):
int responseCode = httpCon.getResponseCode();
And read data from response:
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
If you want to parse JSON you can use org.json or Gson.

Categories

Resources