Vicky
Vicky

Reputation: 33

Server returned HTTP response code: 401 for URL (pass username and password in URL to access a file)

i write a program that will fetch a file specified by a URL. but my code gives me "Server returned HTTP response code: 401 for URL". i googled on this and found that, this error is due to authentication failure. so my question is that : how i can pass my username and password along with my URL?
here is my code

String login="dostix12";
String password="@@@@@";
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URL url = new URL("https://level.x10hosting.com:2083/cpsess5213137721/frontend/x10x3/filemanager/showfile.html?file=factorial.exe&fileop=&dir=%2Fhome%2Fdostix12%2Fetc&dirop=&charset=&file_charset=&baseurl=&basedir=");
url.openConnection();

Upvotes: 1

Views: 11924

Answers (3)

Pankaj Khattar
Pankaj Khattar

Reputation: 111

Use the following the code, it would work:

final URL url = new URL(urlString);
Authenticator.setDefault(new Authenticator()
{
  @Override
  protected PasswordAuthentication getPasswordAuthentication()
  {
    return new PasswordAuthentication(userName, password.toCharArray());
  }
});
final URLConnection connection = url.openConnection();

Upvotes: 4

Juned Ahsan
Juned Ahsan

Reputation: 68715

It will depend on how the server is expecting the credentials. General way of accepting the authentication details is using BASIC authentication mechanism. In Basic authentication, you need to set the Authroization http header.

The Authorization header is constructed as follows:

Username and password are combined into a string "username:password"

The resulting string literal is then encoded using Base64

The authorization method and a space i.e. "Basic " is then put before the encoded string.

For example, if the user agent uses 'Aladdin' as the username and 'open sesame' as the password then the header is formed as follows:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Source : http://en.wikipedia.org/wiki/Basic_access_authentication

Here is a sample code to add the authorization header:

  url = new URL(targetURL);
  connection = (HttpURLConnection)url.openConnection();
  BASE64Encoder enc = new sun.misc.BASE64Encoder();
  String userpassword = username + ":" + password;
  String encodedAuthorization = enc.encode( userpassword.getBytes() );
  connection.setRequestProperty("Authorization", "Basic "+
        encodedAuthorization);

Upvotes: 4

morgano
morgano

Reputation: 17422

You need to send the Authorization header in your HTTP request, in it you should send username and password encoded in base64.

more info here: http://en.wikipedia.org/wiki/HTTP_headers

Upvotes: 0

Related Questions