How to Make a HTTP POST Call with Oracle JDK

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public final class HttpSample {

  public static void main(final String[] args) throws Exception {
    final URL url = new URL("http://host/");

    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setDoOutput(true);

    conn.setRequestMethod("POST"); // "GET" is the default

    final OutputStream out = conn.getOutputStream();

    out.write("param1=value&param2=value".getBytes()); // urlencode when needed

    out.close();

    final int responseCode = conn.getResponseCode();

    if (responseCode < 207) {
      final InputStream in = conn.getInputStream();

      int i = in.read();

      while (i != -1) {
        System.out.print((char)i);

        i = in.read();
      }

      in.close();
    } else {
      final InputStream err = conn.getErrorStream();

      int i = err.read();

      while (i != -1) {
        System.out.print((char)i);

        i = err.read();
      }

      err.close();
    }

    conn.disconnect();
  }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s