问题描述
如何为 httpClient 库的默认客户端添加基本身份验证?我看过他们使用 client.getCredentialProvider()
的例子,但是我认为所有这些方法都适用于库版本 4.0.1 或 3.x.有没有新的例子来说明如何做到这一点?非常感谢.
How do I add basic authentication for the default client of the httpClient library? I have seen examples where they use client.getCredentialProvider()
, however I think all of this methods are for library version 4.0.1 or 3.x. Is there a new example of how to do this? Thanks a lot.
推荐答案
我们使用 HttpClient
进行基本身份验证,但不使用 CredentialProvider
.代码如下:
We do basic authentication with HttpClient
, but we do not use CredentialProvider
. Here's the code:
HttpClient client = factory.getHttpClient(); //or any method to get a client instance
Credentials credentials = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(AuthScope.ANY, credentials);
更新:在评论中指出,HttpClient.getState()
方法可在 API 的 3.x 版.但是,较新版本的 API 不支持该方法.
UPDATE:A stated in the comments, the HttpClient.getState()
methos is available in version 3.x of the API. However, newer versions of the API doesn't support that method.
这篇关于Apache HttpClient(4.1 及更高版本):如何进行基本身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!