RESTClient using HTTP Get Request - java

I am trying to write a JSON Client which uses HTTP GET method,and I am getting an response of 500.The code I have tried is below,Is there any wrong with the same?The request parameter I am trying to set is entityName=Nila and parentEntity=500000001 as parameters.
URL url = new URL("http://192.168.210.74:9763/services/testEntityService?entityName=Nila&parentEntity=500000001");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
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())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Its an internal server error yes the problem is on server side.

Related

Am trying to call a Rest API from java and receiving 302

I am calling a Rest API from my java application but am receiving 302 error but when I tried to call it from the advanced REST client I received 200 which is successful response .
try {
URL url = new URL("http://jsonmock.hackerrank.com/api/football_matches?year="+year+"&page=2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
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())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 100;
}

Unable to read 404 error response body from azure

I am trying to read the response body for an error response(404,400,500) using java application and basic http client. When testing in my local , I am able to get the proper json response. But when I deployed to azure I am getting the error response body in HTML tags.
Error response I got when deployed to azure and testing from there:
400 Error400 error while attempting to access resource
#AddLoggerInAppInsights
public Map exchangeNativeHttpRequest(String url, String jsonPayLoad, String correlationId) {
Map<String,Object> responseMap = null;
try {
URL httpUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty(CLIENT_ID_KEY, System.getenv(CLIENT_ID_VALUE));
conn.setRequestProperty(CLIENT_SECRET_KEY, System.getenv(CLIENT_SECRET_VALUE));
conn.setRequestProperty(CORRELATION_ID, correlationId);
OutputStream os = conn.getOutputStream();
os.write(jsonPayLoad.getBytes());
os.flush();
HttpStatus httpStatus = HttpStatus.valueOf(conn.getResponseCode());
BufferedReader br = null;
if (conn.getResponseCode() == org.apache.http.HttpStatus.SC_OK) {
br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
}else if (conn.getResponseCode() == org.apache.http.HttpStatus.SC_BAD_REQUEST){
br = new BufferedReader(new InputStreamReader(
(conn.getErrorStream())));
}else {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
telemetryClient.trackEvent(correlationId+":" +"Response for Create Breakdown IBMI API from HTTP_CONNECTION: "+sb.toString());
responseMap = new HashMap<>();
responseMap.put("statusCode",httpStatus);
responseMap.put("response", sb.toString());
conn.disconnect();
} catch (MalformedURLException e) {
telemetryClient.trackException(e);
} catch (IOException e) {
telemetryClient.trackException(e);
}
telemetryClient.trackEvent(correlationId+":" +"Returned Response of Create Breakdown IBMI API from HTTP_CLIENT: "+responseMap.toString());
return responseMap;
}

Could somebody explain me how consume web services(REST JSON) made in php from java desktop?

I got this example code but the response is an "Exception in NetClientGet:- java.net.SocketException: Permission denied: connect"
I'm using jdk 1.8.
This is my example code:
try {
URL url = new URL("http://localhost/ServiciosWebLT/peoples");//your url i.e fetch data from .
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
thanks in advance.

java.io.IOException: Server returned HTTP response code: 411

I am trying to post to a server the following URL:
http://localhost:3000/webserver/query?q=AddData(123,2015)
Using the code below, the server is returning error 411.
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
connection.setRequestProperty("Authorization", "Basic " + Base64.encode("administrator:"));
connection.setRequestProperty("Content-Length", "0");
connection.setDoOutput(true);
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while((line = rd.readLine()) != null) {
System.out.println(line);
}
rd.close();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if(connection != null) connection.disconnect();
}
I know that error 411 is an invalid Content-Length method. I have tried giving the Content-Length the length of the URL but the error persisted.
Can you please help with this issue?

POST request to REST API with JSON object as payload

I am trying to get the JSON response from the REST API using the POST request that has JSON payload (should be converted to URL encoded text before sending). I have followed some tutorials to implement the process but I get error with status code 400. I may not be encoding the given JSON string or missing something. Please help me solve this problem. Thanks.
Here is my code
try {
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme#totango.com");
conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
String payload = "{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme#totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}";
OutputStream os = conn.getOutputStream();
os.write(payload.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();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
After following many posts and tutorials for more than 24 hours I got to know that I am not sending my URL parameters correctly. And also I learned that REST API call using ApacheHttpClient is comparatively easier. I resolved my HTTP error code 400 and got the response back from the server. Here is the working code for my issue.
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://appem.totango.com/api/v1/search/accounts/health_dist");
List<NameValuePair> headers = new ArrayList<NameValuePair>(); //ArrayList to store header parameters
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); //ArrayList to store URL parameters
urlParameters.add(new BasicNameValuePair("query","{\"terms\":[{\"type\":\"totango_user_scope\",\"is_one_of\":[\"mobile+testme#totango.com\"]}],\"group_fields\":[{\"type\":\"health\"}]}"));
headers.add(new BasicNameValuePair("app-token", "1a1c626e8cdca0a80ae61b73ee0a1909941ab3d7mobile+testme#totango.com"));
headers.add(new BasicNameValuePair("Accept", "application/json, text/javascript, */*; q=0.01"));
headers.add(new BasicNameValuePair("X-Requested-With", "XMLHttpRequest"));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
for (NameValuePair h : headers)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
The API you are invoking needs a query parameter called "query=true|false".
URL url = new URL("https://appem.totango.com/api/v1/search/accounts/health_dist?query=true");
After adding this param, the HTTP request itself succeeds with status code 200, but the REST call fails with some server side error. Maybe you need a different payload.
I suggest if you are new to REST, try a REST client like POSTMan

Categories

Resources