1

我编写了一个程序,它将获取由 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();
4

3 回答 3

4

使用以下代码,它会工作:

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();
于 2014-11-26T07:18:17.873 回答
4

这将取决于服务器如何期望凭据。接受认证细节的一般方式是使用BASIC认证机制。在基本身份验证中,您需要设置Authroizationhttp 标头。

Authorization 标头的构造如下:

用户名和密码组合成一个字符串“用户名:密码”

然后使用 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);
于 2013-07-25T06:17:56.680 回答
0

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

更多信息在这里:http ://en.wikipedia.org/wiki/HTTP_headers

于 2013-07-25T06:16:55.287 回答