我有一个连接到需要基本身份验证的站点的应用程序。这些站点在运行时提供,在编译时未知。
我正在使用 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);
最佳答案
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);
关于java - HttpClient 4.2、基本身份验证和 AuthScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10850114/