2013-05-08 25 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