Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Request payload to REST API in java?

I want to retrieve the JSON data from the following: https://git.eclipse.org/r/#/c/11376/

Request URL: https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService

Request Method: POST

Request Headers:

Accept:application/json  Content-Type:application/json; charset=UTF-8 

Request Payload:

{"jsonrpc":"2.0","method":"changeDetail","params":[{"id":11376}],"id":1} 

I already tried this answer but I am getting 400 BAD REQUEST.

Can anyone help me sort this out?

Thanks.

like image 395
Gangaraju Avatar asked Mar 22 '13 12:03

Gangaraju


People also ask

How do I send a payload request?

Sending a payload post("https://restful-booker.herokuapp.com/auth"); String authResponse = response. getBody(). print(); assertThat(authResponse, containsString("token")); So we begin by calling AuthPayload to create a new Java Object with the values we want to send in the HTTP POST request.


1 Answers

The following code works for me.

//escape the double quotes in json string String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}"; String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService"; sendPostRequest(requestUrl, payload); 

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {     try {         URL url = new URL(requestUrl);         HttpURLConnection connection = (HttpURLConnection) url.openConnection();          connection.setDoInput(true);         connection.setDoOutput(true);         connection.setRequestMethod("POST");         connection.setRequestProperty("Accept", "application/json");         connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");         OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");         writer.write(payload);         writer.close();         BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));         StringBuffer jsonString = new StringBuffer();         String line;         while ((line = br.readLine()) != null) {                 jsonString.append(line);         }         br.close();         connection.disconnect();         return jsonString.toString();     } catch (Exception e) {             throw new RuntimeException(e.getMessage());     }  } 
like image 128
Gangaraju Avatar answered Sep 21 '22 00:09

Gangaraju