Java:httpbasic認証を使用してURLをフェッチします
-
20-09-2019 - |
質問
私はいくつかの簡単なHTTP認証をしています、そして
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic OGU0ZTc5ODBk(...trimmed from 76 chars...)
(...more password data...)
これは私が本当に長いユーザー名とパスワードを持っていて、エンコーダーがそれをラップしたことだと思います \n
76 chars。これを回避できる方法はありますか? 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のバグ.
Apacheのライブラリなど、代替のHTTPクライアントを使用してみましたか?
または、認証器を使用する代わりに、ヘッダーを手動で設定しますか?
URL url = new URL("http://www.example.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic OGU0ZTc5ODBkABcde....");
トークン値はencodebase64( "username:password")です。
他のヒント
これは私のために働きます。
httpsurlconnection con = null; con =(httpsurlconnection)obj.openconnection(); string encoding = base64.getEncoder()。encodetostring( "username:password" .getBytes(stardingcharsets.utf_8)); con.setRequestProperty( "Authorization"、 "basic"+encoding.replaceall( " n"、 ""));
違法な性格は、「承認:基本」、「承認」、「基本」 +エンコードされたエンコードされた「基本」によって引き起こされることがわかりました。
所属していません StackOverflow