Apache HttpClient (4.1 и новее): как выполнить базовую аутентификацию?

Как добавить базовую аутентификацию для клиента библиотеки httpClient по умолчанию? Я видел примеры, где они используют client.getCredentialProvider(), однако я думаю, что все эти методы предназначены для версии библиотеки 4.0.1 или 3.x. Есть ли новый пример того, как это сделать? Большое спасибо.


person Pablo    schedule 22.02.2012    source источник
comment
Это лучший пример, который я где-либо нашел... намного лучше, чем документация Apache: stackoverflow.com/a/4328694/967980< /а>   -  person Erich    schedule 16.04.2015


Ответы (6)


Мы выполняем базовую аутентификацию с помощью HttpClient, но не используем CredentialProvider. Вот код:

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() доступен в версия 3.x API. Однако более новые версии API не поддерживают этот метод.

person Carlos Gavidia-Calderon    schedule 22.02.2012
comment
Это здорово, но HttpClient.getState() не существует в коде 4.x. Это применимо только для 3.1 и более ранних версий. - person Spanky Quigman; 02.11.2012
comment
Я единственный, кто смущен тем, почему это принятый ответ? - person Kartik Chugh; 03.11.2016

Разве вы не скачали пример с сайта? А примеры здесь: httpcomponents-client-4.1.3\examples\org\apache\http\examples\client

Что касается https, просто посмотрите 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();
        }
    }
}

Итак, вкратце:

DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope("localhost", 443),
                    new UsernamePasswordCredentials("username", "password"));
person Jacob    schedule 02.03.2012
comment
DefaultHttpClient устарел в версии 4.x. Вы можете использовать пример https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java из https://hc.apache.org/httpcomponents-client-ga/examples.html . - person Xdg; 28.07.2014
comment
DefaultHttpClient устарел только в версии 4.3. Он не устарел в 4.1 - person Marco Altieri; 25.06.2016

Еще один современный вариант для 4.3 — использовать расширение Fluent:

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();
person Barett    schedule 09.10.2014
comment
Немного потрудившись, чтобы это работало на https-соединении, не нужно забывать добавить порт и схему на HttpHost (новый HttpHost (somehost, 443, https), поскольку порт и схема по умолчанию — 80, http. - person Olivier; 28.01.2016
comment
Каков полный путь импорта для Executer? Я получаю сообщение об ошибке для .newInstance(). Компилятор говорит, что не существует. Какую версию JDK вы используете? - person Robert Reiz; 27.06.2017
comment

DefaultHttpClient имеет getCredentialsProvider(), а HttpClient — нет. Вам нужно объявить DefaultHttpClient client = ... вместо HttpClient client = ...

person stefan    schedule 24.05.2013
comment
DefaultHttpClient больше не рекомендуется в версии 4.3, несмотря на то, что он появился только в версии 4.0! - person artbristol; 26.03.2014

У меня было требование вызвать URL-адрес с базовой аутентификацией, для которой также требовались настройки прокси. Это то, что сработало для меня.

    import java.io.IOException;
    import java.io.InputStream;
    import java.io.StringReader;
    import java.util.HashMap;
    import java.util.Map;

    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;

    import org.apache.commons.httpclient.Credentials;
    import org.apache.commons.httpclient.HostConfiguration;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpMethod;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.w3c.dom.*;

    import javax.xml.parsers.*;


    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;

    public class TestResponse {

    public final static String TESTURL="https://myURL";
    private static final String PROXY_HOST = "www2.proxyXYS";
    private static final int PROXY_PORT = 8080;


    public static void main (String args[]) 
    {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(TESTURL);
    HostConfiguration config = client.getHostConfiguration();
    config.setProxy(PROXY_HOST, PROXY_PORT);

      String username = "User";
      String password = "Pa55w0rd";


    Credentials credentials = new UsernamePasswordCredentials(username, password);
    AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

    client.getState().setProxyCredentials(authScope, credentials);
    client.getState().setCredentials(AuthScope.ANY, credentials);

    try {
        client.executeMethod(method);

        String response = method.getResponseBodyAsString();

        if (method.getStatusCode() == HttpStatus.SC_OK) {
             response = method.getResponseBodyAsString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}





}
person Amit Singh    schedule 05.01.2017

person    schedule
comment
Это лучший ответ для v4.3. Просто будьте осторожны, так как учетные данные будут отправлены заранее на все URL-адреса. - person artbristol; 26.03.2014
comment
Чтобы решить проблему artbristol, измените файл AuthScope. - person Barett; 10.10.2014
comment
@artbristol Только если у вас настроена вытесняющая аутентификация, верно? HttpClient изначально не поддерживает упреждающую аутентификацию - person bmaupin; 07.04.2020
comment
@bmaupin да, я думаю, ты прав. Это отправит учетные данные на любой сервер, который их требует, но не иначе. - person artbristol; 15.04.2020