Thursday, January 17, 2008

Sending Basic authentication using URL (Java)

When I was doing WSO2 Registry , I wanted to find a way to send basic authentication using just URL , but I search the good however did not find a way to do that so , I tried several ways and finally got that working following code;



URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String authorizationString = “Basic “ + Base64.encode(username:password);
uc.setRequestProperty ("Authorization", authorizationString);
InputStream in = url.openStream();

9 comments:

Mubin Ahmed said...

Hi..
I tried to use the code that you have given in this blog. But it did not work for me. I got the error that the resource requires authentication. Can you please help me out. Its urgent. I need to implement it in one of my projects.
My email-id is skzr.mubin@gmail.com

Thanks in advance.

Deepal Jayasinghe said...

If you set the correct username and password, then the code should work, unless there a problem with the Base64 encoding mechanism you use.

Pulak said...

i have done a small change in the sample code and it works fine. the sample code in given below.

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String val = (new StringBuffer("username").append(":").append("password")).toString();
byte[] base = val.getBytes();
String authorizationString = "Basic " + new String(new Base64().encode(base));
uc.setRequestProperty ("Authorization", authorizationString);
InputStream in = url.openStream();

thanks, it's a great help for me.

learner said...

URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", "Basic " + encoding);

Please note that there is a space after the word Basic in the above statement. It is "Basic " and not "Basic".

If you miss that space character... the code provided by Deepal wouldn't work. That's the problem that I faced.

Hector said...
This comment has been removed by the author.
FTXT said...
This comment has been removed by a blog administrator.
nicu_alex2009 said...

This really is an awesome post, I'm happy I recently found. I have been trying to find guest writers for my blog so if you ever decide that's something you are interested in please feel free to contact me. I will be back to look at out more of your articles later
pariuri sportive

Anonymous said...

Thank you very much, saved me lots of research.

Roses said...

i get this error saying password cannot be resolved to a field