How to Make a HTTP GET Call with Basic Authentication with Oracle JDK

import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

public final class HttpSample {

  public static void main(final String[] args) throws Exception {
    Authenticator.setDefault(new Authenticator() {

      public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("user", "password".toCharArray());
      }

    });

    final URL url = new URL("http://host/"); // If there are parameters, just concatenate them to the URL

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

    final int responseCode = conn.getResponseCode();

    final InputStream in = conn.getInputStream();

    if (responseCode == 200) { // OK
      int i = in.read();

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

        i = in.read();
      }

      in.close();
    } else {
      System.out.println(responseCode + " " + conn.getResponseMessage());
    }

    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