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;
}
Related
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;
}
I'm getting a 'Server returned HTTP response code: 500' error although I have checked what I'm sending (I even tried sending it with an online tool and it worked). The API Key and the JSON are correct. I get this error when trying to read the input stream with 'connection.getInputStream()'. Where could this be comming frome ? Did I forget something ? I am trying to implement this feature from the openrouteservice API : https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/post
public static UPSRoute getRoute(Location start, Location end, String language) {
if (language.equals("fr")) {
JSONObject jsonObject = null;
try {
URL url = new URL("https://api.openrouteservice.org/v2/directions/foot-walking");
String payload = "{\"coordinates\":[[" + start.getCoordinates() + "],[" + end.getCoordinates() + "]],\"language\":\"fr\"}";
System.out.println(payload); //{"coordinates":[[1.463478,43.562038],[1.471717,43.560787]],"language":"fr"}
byte[] postData = payload.getBytes(StandardCharsets.UTF_8);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", API_KEY);
connection.setRequestProperty("Accept", "application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8");
connection.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.write(postData);
}
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // Error is right here
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
jsonObject = new JSONObject(content.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return new UPSRoute(jsonObject);
} else {
return getRoute(start, end);
}
}
Here is the error :
java.io.IOException: Server returned HTTP response code: 500 for URL: https://api.openrouteservice.org/v2/directions/foot-walking/json
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1913)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1509)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:245)
at UPSRouteService.getRoute(UPSRouteService.java:63)
at Main.main(Main.java:5)
Thanks to Andreas, it was just missing the line :
connection.setRequestProperty("Content-Type", "application/json");
It works fine now.
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.
Im having trouble getting an access token for the sandbox environment.
Im following this guide for authenticating: OAuth
So when i create my request, following this guide, i get the following response from the api:
{"error":"access_denied","error_description":"Invalid application credentials."}
Im using key for mf client ID and secret as my client secret as per the instructions.
Here is the code Im using:
public static void main(String[] args) {
try {
URL url = new URL("https://www.dwolla.com/oauth/v2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("client_id", "<Key>");
conn.setRequestProperty("client_secret", "<Secret>");
conn.setRequestProperty("grant_type", "client_credentials");
conn.setDoInput(true);
conn.setDoOutput(true);
System.out.println("Message:" + conn.getResponseMessage());
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 ex) {
Logger.getLogger(PaymentTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PaymentTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
I was able to get an access token finally. My problem is first of all the above code uses client_id and client_secret as header params. These need to go in the body of the request.
My second problem is that I used the wrong content type for the message I was sending.
Here is the code that worked for me:
URL url = new URL("https://sandbox.dwolla.com/oauth/v2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String data = "";
JSONObject jsonObj = new JSONObject();
jsonObj.put("client_id", "<Your Client ID>");
jsonObj.put("client_secret", "<Your Client Secret>");
jsonObj.put("grant_type", "client_credentials");
data = jsonObj.toString();
System.out.println("data = " + data);
byte[] outputInBytes = data.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
System.out.println("Message:" + conn.getResponseMessage());
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 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.