2012-05-07 124 views
13

我正在使用Java访问以XML格式返回显示的HTTPS站点。我在URL本身传递登录凭证。这里是代码片段:服务器返回的HTTP响应代码:401的URL:https

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
requestURL = "https://Administrator:[email protected]: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://Administrator:[email protected]:8443/abcd

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

回答

24

401表示“未经授权”,所以必须有您的凭证。

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

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但这只是表明一个快速的解决方案。如果你想保留这个解决方案,找一个能做的库。有很多。

+1

感谢纪尧姆波莱。第二种选择就像魅力一样。我只需要它进行内部测试,所以我认为这可能就够了。 – Vish

+1

谢谢Polet。第二个选项帮助了我。 –

1

试试这个。您需要通过身份验证,让服务器知道其有效的用户。您需要导入这两个软件包,并且必须包含一个jersy jar。如果你不想包括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; 
} 
相关问题