我正在进行一些简单的HTTP身份验证,并且正在获取
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic OGU0ZTc5ODBk(...trimmed from 76 chars...)
(...more password data...)
我认为这是因为我有一个非常长的用户名和密码,编码器用76个字符包裹\n
。有什么方法可以解决这个问题吗?该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;
}
答案 0 :(得分: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”)。
答案 1 :(得分:1)
这适合我。
HttpsURLConnection con = null; con =(HttpsURLConnection)obj.openConnection(); String encoding = Base64.getEncoder()。encodeToString(“username:password”.getBytes(StandardCharsets.UTF_8)); con.setRequestProperty(“授权”,“基本”+ encoding.replaceAll(“\ n”,“”));
答案 2 :(得分:0)
我发现非法字符是由"授权:基本",编码引起的 应该是"授权","基本" +编码
答案 3 :(得分:0)
从“授权:基本”更改为“授权”,“基本” +编码解决了我的标头问题中的非法字符。