use*_*330 6 java httpclient apache-commons-httpclient apache-httpclient-4.x
我有一个应用程序连接到需要基本身份验证的站点.这些站点在运行时提供,在编译时不知道.
我正在使用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);
Run Code Online (Sandbox Code Playgroud)
您正在使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20207 次 |
| 最近记录: |