How to send post request in java with a JSON body

Tags: , , ,



I am confused as to how to send a post request in Java with JSON parameters. I have seen many examples that use HttpPost library which I can not access. Below is my code:

public class endpointtest {

public String endpoint(String urlStr, String username) {

    final StringBuilder response = new StringBuilder();

    try {
        //creating the connection
        URL url = new URL(urlStr);

        HttpClient client = HttpClient.newHttpClient();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.connect();


        //builds the post body, adds parameters
        final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        //out.writeBytes(toJSON(globalId)); 
        out.flush();
        out.close();

        //Reading the response
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputline;

        while ((inputline = in.readLine()) != null) {
            response.append(inputline);
        }
        in.close();

        connection.getResponseCode();
        connection.disconnect();

    } catch (final Exception ex) {

        ex.printStackTrace();
        System.out.println(" error ");
    }

    return response.toString();


}

} class main {

public static void main(String[] args){
    endpointtest ep = new endpointtest();
    ep.endpoint("localhost:8080/endpoint","""
        {
            "name": "mike",
            "Id": "123"
        }
    """);
}
}

I am trying to pass the json in the main method (I know I am not doing it right), and was wondering as to how I would do this correctly.

Answer

This Question is asked before here: HTTP POST using JSON in Java

See it and comment this if you face any problem.



Source: stackoverflow