2010-01-13 51 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

我发现非法字符,通过“授权:基本”引起的,编码 这应该是“授权”,“基本” +编码