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

问题描述 投票:17回答:2

我正在使用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程序中完成这项工作。

java tomcat https http-status-code-401
2个回答
32
投票

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,但这只是为了显示快速解决方案。如果您想保留该解决方案,请查找具有该功能的库。有很多。


1
投票

试试这个。您需要通过身份验证才能让服务器知道其有效用户。你需要导入这两个包,并且必须包含一个jersy jar。如果您不想包含jersy jar,请导入此包

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;
 }
© www.soinside.com 2019 - 2024. All rights reserved.