Java Language HttpURLConnection POST data

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


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);

        out = connection.getOutputStream();

        in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {

    } 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?