HttpClient 4.2、基本身份验证和 AuthScope [英] HttpClient 4.2, Basic Authentication, and AuthScope

查看:95
本文介绍了HttpClient 4.2、基本身份验证和 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.

我使用的是 HttpClient 4.2.

I am using HttpClient 4.2.

我不确定下面的代码是否是我应该如何指定基本身份验证的方式,但文档表明是这样.但是,我不知道要在AuthScope 的构造函数中传递什么.我原以为空参数意味着提供的凭据应该用于所有 URL,但它抛出了 NullPointerException,所以很明显我错了.

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. 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.

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

推荐答案

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

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

这篇关于HttpClient 4.2、基本身份验证和 AuthScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆