Send data in REST API in Java

To send data in REST using Java, you can use the Java HttpURLConnection class. Here's an example of sending data using HttpURLConnection:


import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStreamWriter;

public class RestDataSender {

    public static void main(String[] args) {
        try {
            // Create a URL object with the REST API endpoint
            URL url = new URL("https://example.com/api/data");

            // Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set the request method to POST
            connection.setRequestMethod("POST");

            // Set the request headers
            connection.setRequestProperty("Content-Type", "application/json");

            // Enable output and set the request body
            connection.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("{\"data\": \"Hello, World!\"}");
            writer.flush();

            // Get the response code
            int responseCode = connection.getResponseCode();

            // Close the connection and writer
            writer.close();
            connection.disconnect();

            // Output the response code
            System.out.println("Response code: " + responseCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


In this example, we're sending a JSON payload with a single key-value pair ("data": "Hello, World!"). The payload is written to the output stream of the connection, and the response code is output to the console. Note that you may need to handle exceptions, such as IOException, that may be thrown when creating the connection or writing to the output stream.