简体   繁体   English

HttpClient 4.2,基本身份验证和AuthScope

[英]HttpClient 4.2, Basic Authentication, and AuthScope

I have an application connecting to sites that require basic authentication. 我有一个应用程序连接到需要基本身份验证的站点。 The sites are provided at run time and not known at compile time. 这些站点在运行时提供,在编译时不知道。

I am using HttpClient 4.2. 我正在使用HttpClient 4.2。

I am not sure if the code below is how I am supposed to specify basic authentication, but the documentation would suggest it is. 我不确定下面的代码是否应该如何指定基本身份验证,但文档会建议它。 However, I don't know what to pass in the constructor of AuthScope . 但是,我不知道在AuthScope的构造函数中传递什么。 I had thought that a null parameter meant that the credentials supplied should be used for all URLs, but it throws a NullPointerException , so clearly I am wrong. 我原以为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);

AuthScope.ANY is what you're after: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/auth/AuthScope.html 您正在使用AuthScope.ANY: http ://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/auth/AuthScope.html

Try this: 尝试这个:

    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);

From at least version 4.2.3 (I guess after version 3.X), the accepted answer is no longer valid. 从至少版本4.2.3(我猜版本3.X之后),接受的答案不再有效。 Instead, do something like: 相反,做一些像:

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

The JavaDoc for AuthScope.ANY says In the future versions of HttpClient the use of this parameter will be discontinued , so use it at your own risk. AuthScope.ANY的JavaDoc说在HttpClient的未来版本中,将停止使用此参数 ,因此使用它需要您自担风险。 A better option would be to use one of the constructors defined in AuthScope . 更好的选择是使用AuthScope定义的构造函数之一。

For a discussion on how to make requests preemptive, see: 有关如何提出抢先请求的讨论,请参阅:

Preemptive Basic authentication with Apache HttpClient 4 使用Apache HttpClient进行抢占式基本身份验证4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM