Apache HttpClient (4.1 and newer): how to do basic authentication?

前端 未结 6 1881
予麋鹿
予麋鹿 2021-01-30 16:33

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 th

6条回答
  •  一生所求
    2021-01-30 17:20

    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);
    

    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.

提交回复
热议问题