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

81,578

Solution 1

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.

Solution 2

CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, 
    new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient = 
    HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();

Solution 3

Didn't you download the example from the website?And examples are here: httpcomponents-client-4.1.3\examples\org\apache\http\examples\client

As for https,Just see ClientAuthentication.java:

/*
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.http.examples.client;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
 * A simple example that uses HttpClient to execute an HTTP request against
 * a target site that requires user authentication.
 */
public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));

            HttpGet httpget = new HttpGet("https://localhost/protected");

            System.out.println("executing request" + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
    }
}

So in short :

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));

Solution 4

Another modern option for 4.3 is to use the Fluent extension:

Executor executor = Executor.newInstance()
        .auth(new HttpHost("somehost"), "username", "password")
        .auth(new HttpHost("securehost", 443, "https"), "username", "password") // https example
        .auth(new HttpHost("myproxy", 8080), "username", "password")
        .authPreemptive(new HttpHost("myproxy", 8080));

String content = executor.execute(Request.Get("http://somehost/"))
        .returnContent().asString();

Solution 5

DefaultHttpClient has getCredentialsProvider() but HttpClient doesn't. You need to declare DefaultHttpClient client = ... instead of HttpClient client = ...

Share:
81,578

Related videos on Youtube

Pablo
Author by

Pablo

Updated on January 05, 2020

Comments

  • Pablo
    Pablo over 4 years

    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.

  • Spanky Quigman
    Spanky Quigman over 11 years
    That's great, but HttpClient.getState() doesn't exist in the 4.x code. This is only applicable for 3.1 and earlier.
  • artbristol
    artbristol about 10 years
    This is the best answer for v4.3. Just be careful that it will send the credentials preemptively to all URLs.
  • artbristol
    artbristol about 10 years
    DefaultHttpClient is now deprecated in 4.3, despite only being introduced in 4.0!
  • Xdg
    Xdg over 9 years
  • Barett
    Barett over 9 years
    To solve for artbristol's concern, change the AuthScope.
  • Olivier
    Olivier about 8 years
    Having struggle a bit to make this work on an https connection, one need no to forget to add port and scheme on HttpHost (new HttpHost("somehost", 443, "https"), as default port and scheme are 80, http.
  • Marco Altieri
    Marco Altieri almost 8 years
    DefaultHttpClient has been deprecated only in 4.3. It is not deprecated in 4.1
  • Kartik Chugh
    Kartik Chugh over 7 years
    Am I the only one confused as to why this is the accepted answer?
  • Robert Reiz
    Robert Reiz almost 7 years
    What is the full import path for Executer? I'm getting an error for .newInstance(). Compiler says that doesn't exist. Which version of JDK are you using?
  • Barett
    Barett almost 7 years
  • bmaupin
    bmaupin about 4 years
    @artbristol Only if you have preemptive auth configured, right? "HttpClient does not support preemptive authentication out of the box"
  • artbristol
    artbristol about 4 years
    @bmaupin yes I think you're right. This will send the credentials to any server that demands them, but not otherwise.