服务器响应401,服务器返回的HTTP响应代码:401网址:https(Server returned HTTP re

我使用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网址: https://开头管理员:密码@本地:8443 / ABCD

我可以用我的浏览器相同的URL并正确显示XML。 请让我知道如何使Java程序中这项工作。

Answer 1:

401的意思是“未经授权”,因此必须有一些与您的凭据。

我认为Java URL不支持你是显示的语法。 你可以使用一个验证器来代替。

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但这只是表明一个快速的解决方案。 如果你想保住你的解决方案,寻找那些确实库。 有很多。

Answer 2:

试试这个。 你需要通过认证让服务器知道它的有效用户。 您需要导入这两个包,并具有包括jersy罐子。 如果你不想包括jersy罐子然后导入这个包

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;

import sun.net.www.protocol.http.HttpURLConnection;

然后,

String encodedAuthorizedUser = getAuthantication("username", "password");

URL url = new URL("Your Valid Jira URL");

HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

public String getAuthantication(String username, String password) {

String auth = new String(Base64.encode(username + ":" + password));

return auth;

}

文章来源: Server returned HTTP response code: 401 for URL: https

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值