Philo Philo - 3 months ago 15
JSON Question

Java: BufferedReader and WebAPI response

I have a bufferedReader that is accepting response from a WebAPI for an httpPost request.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");

/* send http-POST request to webAPI */
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();


BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));


The data contained in 'br' as a result of a httpPost request made to the webapi:-

{
"xx" : "...."
"yy" : "...."
"zz" : "...."
}
HTTP/1.1 202... blah blah blah
Content-Length: 35
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Connection: close


First of all I would like to point out that it is weird that I am getting header information in the response itself...but only for JAVA.. ( I code the same thing with C#, which is where I am most proficient and didn't receive any header information back). Is this even possible? since... in my understanding, what the webapi responds is independent of C# or Java code?

Now my main objective is to extract the value for the key 'zz'.

I was trying something like:-

JSONParser parser = new JSONParser();
try
{
JSONObject json = (JSONObject) parser.parse(br);
}
catch (org.json.simple.parser.ParseException e)
{
e.printStackTrace();
}


However because of the weird HTTP/202 response part of the message, I am getting an error "Unexpected character (H) at position 281".

So, I am thinking, maybe I need to truncate my buffer 'br' before I try to use JSON. I am wondering what is the best way of doing this?

Answer

Doing it through json will make it more complex because you'd have first convert it into proper json in order to allow json parser to parse.

A more optimal way to do it would be through Regular Expressions

Input

{
   xx : 
   yy :
   zz : sample 123123
}
HTTP/1.1 202... blah blah blah
Content-Length: 35
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Connection: close

Regular Expression

.*zz\s*:\s*(.*)[\n\r]/g

Output

sample 123123

See this link for more details

Comments