1

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.

2 Answers2

2

This is the simplest way to do it.

public class Main {
    public static void main(String[] args) throws IOException {
    String apiUrl = "http://myserver/rest/V1.0/manage/export"; // Your api/http link
    String userName = "admin"; // Your username
    String password = "adminpro"; // Your password

        sendRequest(basicUrl, userName, password);
}
public static void sendRequest(String apiurl,String userName,String password){
    try{
        URL url = new URL(apiurl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type","application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((userName + ":" + password).getBytes()));
        String payload = "{\"sampleKey\":\"sampleValue\"}";// This should be your json body i.e. {"Name" : "Mohsin"} 
        byte[] out = payload.getBytes(StandardCharsets.UTF_8);
        OutputStream stream = connection.getOutputStream();
        stream.write(out);
        System.out.println(connection.getResponseCode() + " " + connection.getResponseMessage()); // THis is optional
        connection.disconnect();
    }catch (Exception e){
        System.out.println(e);
        System.out.println("Failed successfully");
    }
}
}
Mohsin Asif
  • 108
  • 4
0

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

See it and comment this if you face any problem.

Atef Magdy
  • 90
  • 9