简体   繁体   中英

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();

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 ie "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);

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();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM