9

私はいくつかの単純なHTTP認証を行っており、

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;
}
4

4 に答える 4

17

これはJavaのバグのようです。

Apacheのライブラリなど、代替のHTTPクライアントを使用してみましたか?

または、オーセンティケーターを使用する代わりに、ヘッダーを手動で設定しますか?

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

トークン値はencodeBase64( "username:password")です。

于 2010-01-13T06:02:09.067 に答える
1

これは私のために働きます。

HttpsURLConnection con = null; con =(HttpsURLConnection)obj.openConnection(); 文字列エンコーディング=Base64.getEncoder()。encodeToString( "username:password" .getBytes(StandardCharsets.UTF_8)); con.setRequestProperty( "Authorization"、 "Basic" + encoding.replaceAll( "\ n"、 ""));

于 2017-01-09T09:33:40.507 に答える
0

不正な文字は「Authorization:Basic」が原因であることがわかりました。エンコードされているのは「Authorization」、「Basic」+エンコードである必要があります。

于 2017-06-01T12:44:48.947 に答える
0

「Authorization:Basic」からエンコードされた「Authorization」、「Basic」+エンコードに変更すると、ヘッダーの問題で不正な文字が解決されました。

于 2020-06-08T05:11:12.903 に答える