繁体   English   中英

服务器返回HTTP响应代码:URL的401(在URL中传递用户名和密码以访问文件)

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

我编写了一个程序,该程序将获取URL指定的文件。 但我的代码给了我“服务器返回的HTTP响应代码:URL 401”。 我对此进行了搜索,发现此错误是由于身份验证失败所致。 所以我的问题是:如何传递用户名和密码以及URL?
这是我的代码

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

这将取决于服务器如何期望凭证。 接受身份验证详细信息的一般方法是使用BASIC身份验证机制。 在基本身份验证中,您需要设置Authroization http标头。

Authorization标头的构造如下:

用户名和密码合并为字符串“ username:password”

然后使用Base64对生成的字符串文字进行编码

然后将授权方法和一个空格(即“ Basic”)放在编码的字符串之前。

例如,如果用户代理使用“ Aladdin”作为用户名,并使用“ open sesame”作为密码,则标头的格式如下:

授权:基本QWxhZGRpbjpvcGVuIHNlc2FtZQ ==

资料来源: http : //en.wikipedia.org/wiki/Basic_access_authentication

以下是添加授权标头的示例代码:

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

使用以下代码,它将起作用:

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

您需要在HTTP请求中发送Authorization标头,在其中应发送以base64编码的用户名和密码。

此处提供更多信息: http : //en.wikipedia.org/wiki/HTTP_headers

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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