HttpClient 4.2, Basic Authentication, and AuthScope

心不动则不痛 提交于 2019-12-05 09:10:55

AuthScope.ANY is what you're after: 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);
Magnilex

From at least version 4.2.3 (I guess after version 3.X), the accepted answer is no longer valid. 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. A better option would be to use one of the constructors defined in AuthScope.

For a discussion on how to make requests preemptive, see:

Preemptive Basic authentication with Apache HttpClient 4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!