Server returned HTTP response code: 401 for URL: https

Vish picture Vish · May 7, 2012 · Viewed 113.7k times · Source

I'm using Java to access a HTTPS site which returns the display in an XML format. I pass the login credentials in the URL itself. Here is the code snippet:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
requestURL = "https://Administrator:Password@localhost:8443/abcd";

try { 
    InputStream is = null;
    URL url = new URL(requestURL);
    InputStream xmlInputStream =new URL(requestURL).openConnection().getInputStream();
    byte[] testByteArr = new byte[xmlInputStream.available()];
    xmlInputStream.read(testByteArr);
    System.out.println(new String(testByteArr));
    Document doc = db.parse(xmlInputStream);
    System.out.println("DOC="+doc);
} catch (MalformedURLException e) {
} 

I'm creating a trust manager in the program which does not validate signed/unsigned certificates. But, on running the above program, I get the error Server returned HTTP response code: 401 for URL: https://Administrator:Password@localhost:8443/abcd

I can use the same url on my browser and it displays the xml correctly. Kindly let me know how to make this work within the Java program.

Answer

Guillaume Polet picture Guillaume Polet · May 7, 2012

401 means "Unauthorized", so there must be something with your credentials.

I think that java URL does not support the syntax you are showing. You could use an Authenticator instead.

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

and then simply invoking the regular url, without the credentials.

The other option is to provide the credentials in a Header:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.