2013-05-08 24 views
1

我想通过连接到URL读取一个XML文件并读取输入流,但我有一个错误 “java.io.IOException:服务器返回的HTTP响应代码:401网址:https:// ......”错误401,而试图连接到URL读取xml

我通过验证器类

这里处理身份验证的情况下是代码:

private static InputStream getConnection(String url) { 
     InputStream in = null; 
     try { 

      final String login="[email protected]"; 
      final String password="password"; 

      Authenticator.setDefault(new Authenticator() { 

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

       } 
      }); 

      URL myUrl = new URL(url); 


      URLConnection urlConn = myUrl.openConnection(); 
      urlConn.connect(); 
      in = urlConn.getInputStream(); 




     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return in; 
    } 
+0

如何使用'Authenticator'将证书传递给服务器?不知道你是否检查过服务器支持的认证类型(基本/形式等)。 – Santosh 2013-05-08 12:08:42

回答

1

试试下面的代码Source

private static InputStream getConnection(String url) { 
    InputStream in = null; 
    try { 

     final String login="[email protected]"; 
     final String password="password"; 

     Authenticator.setDefault(new Authenticator() { 

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

      } 
     }); 

     URL myUrl = new URL(url); 


     URLConnection urlConn = myUrl.openConnection(); 

     urlConn .setDoInput(true); 

     // stuff the Authorization request header 
     byte[] encodedPassword = (login + ":" + password).getBytes(); 
     BASE64Encoder encoder = new BASE64Encoder(); 
     urlConn .setRequestProperty("Authorization", 
         "Basic " + encoder.encode(encodedPassword)); 


     urlConn.connect(); 
     in = urlConn.getInputStream(); 




    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return in; 
} 
+0

同样的问题,错误401, 我需要问一个问题。 主机可以控制我如何连接URL并进行身份验证? – 2013-05-08 13:02:48

+0

是它在服务器上受控...我的代码假设您的服务器正在使用基本身份验证。所以虽然设置requestProperty我设置'基本',然后编码的用户名和密码 – 2013-05-08 13:06:54

+0

谢谢rahul,我感谢您的回应,我会与他们沟通 – 2013-05-08 13:24:40