服务器返回 HTTP 响应代码:401 用于 URL:https [英] Server returned HTTP response code: 401 for URL: https
问题描述
我正在使用 Java 访问一个 HTTPS 站点,该站点以 XML 格式返回显示.我在 URL 本身中传递登录凭据.这是代码片段:
I'm using Java to access a HTTPS site which returns the display in an XML format. I pass the login credentials in the URL itself. Here is the code snippet:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
requestURL = "https://Administrator:Password@localhost:8443/abcd";
try {
InputStream is = null;
URL url = new URL(requestURL);
InputStream xmlInputStream =new URL(requestURL).openConnection().getInputStream();
byte[] testByteArr = new byte[xmlInputStream.available()];
xmlInputStream.read(testByteArr);
System.out.println(new String(testByteArr));
Document doc = db.parse(xmlInputStream);
System.out.println("DOC="+doc);
} catch (MalformedURLException e) {
}
我正在程序中创建一个不验证签名/未签名证书的信任管理器.但是,在运行上述程序时,出现错误服务器返回 HTTP 响应代码:401 for URL:https://Administrator:Password@localhost:8443/abcd
I'm creating a trust manager in the program which does not validate signed/unsigned certificates. But, on running the above program, I get the error Server returned HTTP response code: 401 for URL: https://Administrator:Password@localhost:8443/abcd
我可以在浏览器上使用相同的 url,它可以正确显示 xml.请让我知道如何在 Java 程序中完成这项工作.
I can use the same url on my browser and it displays the xml correctly. Kindly let me know how to make this work within the Java program.
推荐答案
401 的意思是未经授权",所以你的凭据肯定有问题.
401 means "Unauthorized", so there must be something with your credentials.
我认为 java URL
不支持您显示的语法.您可以改用身份验证器.
I think that java URL
does not support the syntax you are showing. You could use an Authenticator instead.
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, password.toCharArray());
}
});
然后简单地调用常规 url,没有凭据.
and then simply invoking the regular url, without the credentials.
另一种选择是在标题中提供凭据:
The other option is to provide the credentials in a Header:
String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);
PS:不建议使用 Base64Encoder,但这只是为了显示快速解决方案.如果您想保留该解决方案,请寻找可以这样做的库.有很多.
PS: It is not recommended to use that Base64Encoder but this is only to show a quick solution. If you want to keep that solution, look for a library that does. There are plenty.
这篇关于服务器返回 HTTP 响应代码:401 用于 URL:https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!