2010-01-13 64 views
9

我做一些簡單的HTTP認證時,出現了的Java:與HTTPBasic抓取網址驗證

java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic OGU0ZTc5ODBk(...trimmed from 76 chars...) 
(...more password data...) 

我想這是因爲我有一個很長的用戶名和密碼和編碼器與包裝它\n在76個字符。有什麼方法可以解決這個問題嗎?該URL僅支持HTTP基本身份驗證。

這裏是我的代碼:

private class UserPassAuthenticator extends Authenticator { 
    String user; 
    String pass; 
    public UserPassAuthenticator(String user, String pass) { 
     this.user = user; 
     this.pass = pass; 
    } 

    // This method is called when a password-protected URL is accessed 
    protected PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(user, pass.toCharArray()); 
    } 
} 

private String fetch(StoreAccount account, String path) throws IOException { 
    Authenticator.setDefault(new UserPassAuthenticator(account.getCredentials().getLogin(), account.getCredentials().getPassword())); 

    URL url = new URL("https", account.getStoreUrl().replace("http://", ""), path); 
    System.out.println(url); 

    URLConnection urlConn = url.openConnection(); 
    Object o = urlConn.getContent(); 
    if (!(o instanceof String)) 
     throw new IOException("Wrong Content-Type on " + url.toString()); 

    // Remove the authenticator back to the default 
    Authenticator.setDefault(null); 
    return (String) o; 
} 
+0

的安全通知:如果通過HTTP使用的用戶名和密碼,這兩個事情發送清晰的字符串。最好使用不同的身份驗證(表單,POST)和傳輸協議(HTTPS,H2)。 – tfb785 2017-06-01 12:50:11

回答

17

這似乎是一個bug in Java

您是否嘗試過使用替代HTTP客戶端,例如Apache的庫?

或者不使用Authenticator,手動設置標題?

URL url = new URL("http://www.example.com/"); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setRequestProperty("Authorization", "Basic OGU0ZTc5ODBkABcde...."); 

令牌值爲encodeBase64(「username:password」)。

+8

只要我從你的bug帖子中解決問題,效果很好。 \t \t'String encoding = new sun.misc.BASE64Encoder()。encode(userpass.getBytes()); \t \t // Java bug:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459815 \t \t encoding = encoding.replaceAll(「\ n」,「」);'。謝謝 – 2010-01-13 07:00:05

+1

對Atlassian REST API(如Bamboo)進行身份驗證時,64字符密碼仍然失敗。在我的情況下替換換行符是不夠的。 Groovy HTTPBuilder和AHC正確處理長密碼。 – 2012-08-28 12:01:04

+0

謝謝甲骨文用這種白癡浪費我30分鐘的時間。 (答覆upvoted,真誠的感謝) – cbmanica 2014-07-08 19:16:25

1

這對我有用。

HttpsURLConnection con = null; con =(HttpsURLConnection)obj.openConnection(); String encoding = Base64.getEncoder()。encodeToString(「username:password」.getBytes(StandardCharsets.UTF_8)); con.setRequestProperty(「Authorization」,「Basic」+ encoding.replaceAll(「\ n」,「」));

0

我發現非法字符,通過「授權:基本」引起的,編碼 這應該是「授權」,「基本」 +編碼