Send JSON data in Java

Here's an example Java code snippet that sends JSON data as a string:

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;

public class SendJSONData {

    public static void main(String[] args) throws Exception {

        // create a JSON object
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("name", "John");
        jsonObj.put("age", 30);
        jsonObj.put("city", "New York");

        // convert JSON object to string
        String jsonStr = jsonObj.toString();

        // specify the URL to send the JSON data to
        String urlStr = "https://example.com/api/data";

        // create a URL object
        URL url = new URL(urlStr);

        // create an HTTP connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        // send the JSON data as a string
        OutputStream os = conn.getOutputStream();
        os.write(jsonStr.getBytes());
        os.flush();

        // read the response from the server
        int responseCode = conn.getResponseCode();
        System.out.println("Response code: " + responseCode);

        // close the connection and output stream
        os.close();
        conn.disconnect();
    }
}


In this example, we create a JSON object using the JSONObject class from the org.json package, and then convert it to a string using the toString() method. We then specify the URL to send the JSON data to, and create an HTTP connection using the HttpURLConnection class. We set the request method to POST, and set the content type header to application/json.


We then send the JSON data as a string using the output stream of the HTTP connection, and read the response code from the server. Finally, we close the connection and output stream.