【问题标题】:Server returned HTTP response code: 401 for URL: https服务器返回 HTTP 响应代码:401 用于 URL:https
【发布时间】:2012-05-15 19:18:41
【问题描述】:

我正在使用 Java 访问一个 HTTPS 站点,该站点以 XML 格式返回显示。我在 URL 本身中传递登录凭据。这是代码sn-p:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢纪尧姆·波莱特。第二个选项就像一个魅力。我只需要它进行内部测试,所以我认为这可能就足够了。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2015-03-22
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多