Thursday, 12 October 2017

Basic authentication using HttpURLConnection

Below statements are used to perform basic authentication.

HttpURLConnection httpUrlConnection = getURLConnection(url);
Encoder encoder = Base64.getEncoder();
String encoded = encoder.encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8));
httpUrlConnection.setRequestProperty("Authorization", "Basic " + encoded);

Find the below working application.

Test.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Base64.Encoder;

public class Test {

 private static HttpURLConnection getURLConnection(String urlToConnect) throws IOException {
  URL url = new URL(urlToConnect);
  HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
  return httpUrlConnection;
 }

 private static InputStream getContent(HttpURLConnection httpUrlConnection) throws IOException {
  int responseCode = httpUrlConnection.getResponseCode();
  InputStream inputStream = null;

  if (responseCode >= 200 && responseCode < 400) {
   inputStream = httpUrlConnection.getInputStream();
  } else {
   inputStream = httpUrlConnection.getErrorStream();
  }

  return inputStream;
 }

 private static void printInputStream(InputStream inputStream) throws IOException {
  BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

  String line = null;

  while ((line = br.readLine()) != null) {
   System.out.println(line);
  }
 }

 public static void main(String[] args) throws IOException {
  String userName = "";
  String password = "";

  String url = "";

  HttpURLConnection httpUrlConnection = getURLConnection(url);
  Encoder encoder = Base64.getEncoder();
  String encoded = encoder.encodeToString((userName + ":" + password).getBytes(StandardCharsets.UTF_8));
  httpUrlConnection.setRequestProperty("Authorization", "Basic " + encoded);

  InputStream inputStream = getContent(httpUrlConnection);
  printInputStream(inputStream);

 }

}


Previous                                                 Next                                                 Home

No comments:

Post a Comment