gpt4 book ai didi

java - 服务器返回 HTTP 响应代码 : 401 for URL (pass username and password in URL to access a file)

转载 作者:行者123 更新时间:2023-11-29 10:16:04 25 4
gpt4 key购买 nike

我编写了一个程序,它将获取由 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 header 。

Authorization header 构造如下:

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:

授权:基本QWxhZGRpbjpvcGVuIHNlc2FtZQ==

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

这是添加授权 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);

关于java - 服务器返回 HTTP 响应代码 : 401 for URL (pass username and password in URL to access a file),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17850389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com