Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

Advertisement
XyzWs Java FAQ: How to add BASIC Authentication into HttpURLConnection?

How to add BASIC Authentication into HttpURLConnection?


Here is one sample.

    ...
    try {
      //Create connection
      url = new URL(targetURL);
      connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      ...
      BASE64Encoder enc = new sun.misc.BASE64Encoder();
      String userpassword = username + ":" + password;
      String encodedAuthorization = enc.encode( userpassword.getBytes() );
      connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
      ...
      //Send post data
      ...

    } catch (Exception e) {
      ...
    } finally {

      if(connection != null) {
        connection.disconnect(); 
      }
    }
  }
  ...

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help