HttpClient 4.2,基本身份验证和AuthScope

时间:2012-06-01 12:18:46

标签: java httpclient apache-httpclient-4.x apache-commons-httpclient

我有一个应用程序连接到需要基本身份验证的网站。这些站点在运行时提供,在编译时不知道。

我正在使用HttpClient 4.2。

我不确定下面的代码是否应该指定基本身份验证,但文档会建议它。但是,我不知道在AuthScope的构造函数中传递什么。我原以为null参数意味着所提供的凭据应该用于所有URL,但它会抛出NullPointerException,所以显然我错了。

m_client = new DefaultHttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(m_userName, m_password);
((DefaultHttpClient)m_client).getCredentialsProvider().setCredentials(new AuthScope((HttpHost)null), credentials);

2 个答案:

答案 0 :(得分:8)

AuthScope.ANY就是你所追求的:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/auth/AuthScope.html

试试这个:

    final HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user.getUsername(), user.getPassword()));
    final GetMethod method = new GetMethod(uri);
    client.executeMethod(method);

答案 1 :(得分:3)

至少从版本4.2.3开始(我想在版本3.X之后),接受的答案不再有效。相反,做一些像:

private HttpClient createClient() {
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    Credentials credentials = new UsernamePasswordCredentials("user", "password");
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);

    return httpclient;
}

AuthScope.ANY的JavaDoc说在HttpClient的未来版本中,将停止使用此参数,因此使用它需要您自担风险。更好的选择是使用AuthScope中定义的构造函数之一。

有关如何提出请求抢先的讨论,请参阅:

Preemptive Basic authentication with Apache HttpClient 4