Java Language HttpURLConnection POST data

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

public static void post(String url, byte [] data, String contentType) throws IOException {
    HttpURLConnection connection = null;
    OutputStream out = null;
    InputStream in = null;

    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestProperty("Content-Type", contentType);
        connection.setDoOutput(true);

        out = connection.getOutputStream();
        out.write(data);
        out.close();

        in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        in.close();

    } finally {
        if (connection != null) connection.disconnect();
        if (out != null) out.close();
        if (in != null) in.close();
    }
}

This will POST data to the specified URL, then read the response line-by-line.

How it works

  • As usual we obtain the HttpURLConnection from a URL.
  • Set the content type using setRequestProperty, by default it's application/x-www-form-urlencoded
  • setDoOutput(true) tells the connection that we will send data.
  • Then we obtain the OutputStream by calling getOutputStream() and write data to it. Don't forget to close it after you are done.
  • At last we read the server response.


Got any Java Language Question?