Get body of Bad Request httpURLConnection.getInputStream() - httpurlconnection

I've been working on a portlet that calls Rest API. When the API is called and the requested data doesn't exist, it returns an appropriate error message in JSON format (with Bad request http code - 400), and if the id exists, it returns the requested data in json (with code 200).
How can I get the body of response (that contains error description) because invoking httpConn.getInputStream() method throws exception in case the response is bad request error.
Code:
HttpURLConnection httpConn = null;
URL url = new URL("http://192.168.1.20/personinfo.html?id=30");
URLConnection connection = url.openConnection();
httpConn = (HttpURLConnection) connection;
httpConn.setRequestProperty("Accept", "application/json");
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("charset", "utf-8");
BufferedReader br = null;
if (!(httpConn.getResponseCode() == 400)) {
br = new BufferedReader(new InputStreamReader((httpConn.getInputStream())));
String output;
StringBuilder builder = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
builder.append(output);
return builder.toString();
}else
here should catch the error message. :)

In case of non-successful response codes, you have to read the body with HttpURLConnection.getErrorStream().

you can get body of Bad Request in HttpURLConnection using this code :
InputStream errorstream = connection.getErrorStream();
String response = "";
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(errorstream));
while ((line = br.readLine()) != null) {
response += line;
}
Log.d("body of Bad Request HttpURLConnection", "Response: " + response);

Use Apache Httpclient:
String url = "http://192.168.1.6:7003/life/lifews/getFirstInstallment.html?rootPolicyNo=1392/2126/2/106/9995/1904&token=1984";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null)
result.append(line);
System.out.println(result);

Related

Java - Bing Spatial Data Services : <title>Object moved to....</title>

I'm trying to use Bing Spatial Data Service of Microsoft by using Java from my server. (I used this code : How to send HTTP request in java?) but it doesnt work at all.
What I want to do: get latitude and longitude from a given adress
public static void main(String[] args) throws IOException {
System.out.println(SendRequete());
}
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
HttpURLConnection connection = null;
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
I keep having the same results:
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
</body></html>ed to here.</h2>
ml><head><title>Object moved</title></head><body>
If I copy and paste on y browser it works fine... Any idea of where the problem is
Looks like you are using the Bing Maps REST services not the Bing Spatial Data Services. The REST services can geocode individual locations on demand, while the Spatial Data Services can geocode up to 200,000 locations in a single request.
Assuming you mean the REST services, yes, the URL you are creating is correct. However you are passing in part of the URL as URL parameters when you shouldn't be. Also, you need to make a GET request, not a POST request. Here is a modified version of your code that should work.
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
URL url = new URL(targetURL + urlParameters);
URLConnection connection = url.openConnection();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Hi All, I am struggling in rest API where i need to post an XML in body with header and get the response, can anyone post an example of how to do it?

String reqURL = baseUrl + data_oauth.get(PropLoad.getTestXmlData("URL"));
Template template = new Template();
String updatedUrl = template.getUpdatedURL(reqURL);
Map<String, String> headers = Template.getRequestData(data_oauth,PropLoad.getTestXmlData("HEADER"));
headers.entrySet().toString();
String updatedAuthor = template.getAuthorizationHeader(headers, methodDesc);
headers.put("Authorization", updatedAuthor);
String xmlRequest = Template.generateStringFromResource(data_oauth,"xmlbody");
Response response = webCredentials_rest.postCallWithHeaderAndBodyParamForXml(headers, xmlRequest, updatedUrl);
// am getting Unmarshalled as in response, can any help me on posting an POST request with XML body in it
You can send it like this:
URL url = new URL(urlString);
URLConnection connenction = url.openConnection();
OutputStream output = connenction.getOutputStream();
InputStream input = new FileInputStream(xmlFile);
byte[] buffer = new byte[4096];
int len;
while ((len = input .read(buffer)) >= 0) {
out.write(buffer, 0, len);
}
input .close();
output.close();
And read the response like this:
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connenction.getInputStream()));
String readLine = reader.readLine();
while (readLine != null) {
stringBuilder.append(readLine);
readLine = br.readLine();
}

while using HttpURLConnection is it necessary to use disconnect()

Can anyone please explain what will be the impact if I dont use disconnect() while using HttpURLConnection. I am sending and recieving data through the connection. and closing the input and output streams. Is that enough or I should explicitely use disconnect().
URL url = new URL(urlname);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("POST");
urlconnection.setDoOutput(true);
urlconnection.setConnectTimeout(s_time);
OutputStreamWriter out = new OutputStreamWriter(urlconnection.getOutputStream());
out.write(postData);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
String somestring;
while ((somestring = in.readLine()) != null) {
data += somestring;
}
in.close();

Parsing JSonObject response by Rest client java

I have written the RestClient to call the rest service and then parse the response. I use this:
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
jObj = new JSONObject(json);
return jObj;
I m getting response like this :
{\"r\":{\"#status\":\"ok\",\"#st\":\"ok\",\"#call_id\":\"8410e\",\"method\":\"notification\",\"notification\":" +
"{\"#status\":\"true\",\"n\":{\"objects\":{\"#totalClassCount\":\"35\",\"#totalTestCount\":\"0\",\"#totalContentCount\":\"0\"," +
"\"#totalAssignmentCount\":\"5\",\"#totalOverdueCount\":\"16\",\"#totalCourseCount\":\"97\",\"#lastClassTime\":\"01-01-1753 12:00:00\"," +
"\"#lastTestTime\":\"01-01-1753 08:00:00\",\"#lastContentTime\":\"09-01-2015 02:52:30\",\"#lastAssgnTime\":\"01-01-1753 08:00:00\"," +
"\"#lastOverdueTime\":\"01-01-1753 12:00:00\",\"#lastCourseTime\":\"09-01-2015 02:52:30\",\"#lastCommentTime\":\"14-12-2015 03:48:55\"," +
"\"flag\":\"1\",\"object\":[{\"#type\":\"3\",\"content\":{\"#contentid\":\"137\",\"ntype\":\"1\",\"sime\":\"9 months ago\"," +
"\"title\":{\"#cdata-section\":\"xlsx icon file\"},\"courseid\":\"95137\",\"sid\":\"1976\",\"subid\":\"0\",\"coursetype\":\"1\",\"contentsize\":" +
"\"0\",\"csid\":\"2\",\"contenttypeid\":\"6\",\"contentviews\":\"0\",\"totalslides\":\"16\",\"iscreator\":\"0\"}}}]}}}}}
Could you please help me how i can parse it?
Thanks,
itin
The code for converting to JSON is not exactly right - Try JSONObject. you can do better as shown below.
if (httpEntity != null) {
String resultString = EntityUtils.toString(httpEntity);
// parsing JSON and convert String to JSON Object
JSONObject result = new JSONObject(resultString);
return result;

Paypal Rest services - Response: Internal Service Error

This is my code. I am not using Maven or curl.
String encoding = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
encoding = encoding.replaceAll("\n", "");
URL url1 = new URL("https://api.sandbox.paypal.com/v1/oauth2/token");
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("grant_type", "client_credentials");
conn.setRequestProperty("Authorization", "Basic " + encoding);
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() == 500) {
InputStream error = conn.getErrorStream();
BufferedReader er = new BufferedReader(new InputStreamReader(error));
String erLine;
while ((erLine = er.readLine()) != null) {
System.out.println(erLine);
}
}
InputStream content = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
conn.disconnect();
OUTPUT:
500
{"name":"INTERNAL_SERVICE_ERROR","information_link":"https://api.sandbox.paypal.com/docs/api/#INTERNAL_SERVICE_ERROR","debug_id":"023ff49775e72"}
PROBLEM:
Well, when I do this call using curl, it gives me an appropriate response. Are the services not equipped to do communication is this way ?
Can you print your Authorization header and inspect whether it's correctly populated? We are currently returning a HTTP500 if your Authorization header is empty (which we'll change to return a more appropriate error obviously).