服务器返回HTTP响应代码:401为URL:https [英] Server returned HTTP response code: 401 for URL: https

查看:5457
本文介绍了服务器返回HTTP响应代码:401为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为URL: https://管理员:密码@ 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());
    }
});

然后只需调用常规网址,而无需凭据。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆