2

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
    con.setRequestMethod("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");

    con.setDoOutput(true);

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

    OutputStream os = con.getOutputStream();
    os.write(jsonObject.toJSONString().getBytes());

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

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

after flushing output stream?
@Moon Yes, os.flush(); it, then os.close();. After that read the response as I mentioned in my answer.
BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()) ); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); I am using this tough, a slight variation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.