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

我正在使用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) { } 

我正在程序中创建一个信任管理器,它不validation签名/未签名证书。 但是,在运行上述程序时,我收到错误服务器返回的HTTP响应代码:401为URL: https:// Administrator:Password @ localhost:8443 / abcd

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

401表示“未经授权”,因此必须有您的凭据。

我认为java URL不支持您显示的语法。 您可以使用身份validation器。

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

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

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

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

PS:不建议使用该Base64Encoder,但这只是为了显示快速解决方案。 如果您想保留该解决方案,请查找具有此function的库。 有很多。

尝试这个。 您需要通过身份validation才能让服务器知道其有效用户。 你需要导入这两个包,并且必须包含一个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; }