小编典典

服务器返回HTTP响应代码:401,URL:https

tomcat

我正在使用Java访问HTTPS站点,该站点以XML格式返回显示内容。我在URL本身中传递了登录凭据。这是代码片段:

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表示URL:https://
Administrator:Password @ localhost:8443 /
abcd

我可以在浏览器中使用相同的URL,它可以正确显示xml。请让我知道如何在Java程序中完成这项工作。


阅读 972

收藏
2020-06-16

共1个答案

小编典典

401的意思是“未经授权”,因此您的凭据中一定有东西。

我认为Java URL不支持您显示的语法。您可以改用Authenticator。

Authenticator.setDefault(new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {          
        return new PasswordAuthentication(login, password.toCharArray());
    }
});

然后只需调用常规网址即可,无需提供凭据。

另一个选项是在标头中提供凭据:

String loginPassword = login+ ":" + password;
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
URLConnection conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encoded);

PS:不建议使用该Base64Encoder,但这只是为了显示快速解决方案。如果要保留该解决方案,请寻找一个可以使用的库。有很多。

2020-06-16