Java:使用HTTPBasic身份验证获取URL

Pau*_*jan 9 java authentication url http http-authentication

我正在做一些简单的HTTP身份验证,我得到了一个

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

我认为这是因为我有一个非常长的用户名和密码,编码器包含\n76个字符.有什么方法可以解决这个问题吗?该URL仅支持HTTP Basic Auth.

这是我的代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 17

这似乎是Java中的一个错误.

您是否尝试过使用其他HTTP客户端,例如Apache的库?

或者不使用Authenticator,而是手动设置标题?

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

令牌值为encodeBase64("username:password").

  • 只要我从你的bug帖子做修复就行得很好.`String encoding = new sun.misc.BASE64Encoder().encode(userpass.getBytes()); // Java bug:http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459815 encoding = encoding.replaceAll("\n","");`.谢谢 (8认同)