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

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

我认为这是由于我拥有一个非常长的用户名和密码,并且编码器将其包裹 \n 以76个字符。有什么办法可以解决这个问题? 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;
}
有帮助吗?

解决方案

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

您是否尝试过使用替代性HTTP客户端,例如Apache的库?

还是不是使用身份验证器,而是手动设置标题?

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

令牌值是EncodeBase64(“用户名:密码”)。

其他提示

这对我有用。

httpsurlconnection con = null; con =(httpsurlconnection)obj.openconnection();字符串编码= base64.getEncoder()。encodeToString(“用户名:密码” .getBytes(standardCharsets.utf_8)); CON.SETREQUESTPROPERTY(“授权”,“基本”+Encoding.ReplaceAll(“ n”,“”));

我发现非法字符是由“授权:基本”引起的,编码为“授权”,“基本” +编码

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top