Moon Moon - 1 year ago 146
JSON Question

get JSON response while performing POST request with HttpURLConnection

I am using the following code to perform POST requests on a REST API. It is all working fine. What I am being unable to do is after POST is successful the API returns response JSON in body with headers, this JSON has information which I require. I am unable to get the JSON response.

I need this response as this response includes the ID generated by DB. I can see the response while using REST Client plugin of firefox. Need to do implement the same in Java.

enter image description here

String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
String url = "http://serv23/api/contents";
URL obj = new URL(url);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

//Setting the Request Method header as POST

//Prepairing credentials
String cred= "user123:p@ssw0rd";
byte[] encoded = Base64.encodeBase64(cred.getBytes());
String credentials = new String(encoded);

//Setting the Authorization Header as 'Basic' with the given credentials
con.setRequestProperty ("Authorization", "Basic " + credentials);

//Setting the Content Type Header as application/json
con.setRequestProperty("Content-Type", "application/json");

//Overriding the HTTP method as as mentioned in documentation
con.setRequestProperty("X-HTTP-Method-Override", "POST");


JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);

OutputStream os = con.getOutputStream();

WriteLine( con.getResponseMessage() );
int responseCode = con.getResponseCode();

Answer Source

Get the input stream and read it.

String json_response = "";
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(in);
String text = "";
while ((text = br.readLine()) != null) {
  json_response += text;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download