Рубрики
Без рубрики

Примеры базовой аутентификации Apache HttpClient

– Примеры базовой аутентификации Apache HttpClient

В этой статье показано, как использовать Apache HttpClient для выполнения базовой аутентификации HTTP.

P.S Протестировано с HttpClient 4.5.10

	
		org.apache.httpcomponents
		httpclient
		4.5.10
	

Запустите простое Веб-приложение Spring Security, обеспечивающее базовую аутентификацию HTTP , и протестируйте его с помощью HttpClient

1. Базовая Аутентификация

Ключ в том, чтобы настроить Поставщик учетных данных и передайте его в HttpClientBuilder .

package com.mkyong.http;

import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientAuth1 {

    public static void main(String[] args) throws IOException {

        HttpGet request = new HttpGet("http://localhost:8080/books");

        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials("user", "password")
        );

        try (CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(provider)
                .build();
             CloseableHttpResponse response = httpClient.execute(request)) {

            // 401 if wrong user/password
            System.out.println(response.getStatusLine().getStatusCode());   

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // return it as a String
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            }

        }

    }

}

Выход

200
[
	{"id":1,"name":"A Guide to the Bodhisattva Way of Life","author":"Santideva","price":15.41},
	{"id":2,"name":"The Life-Changing Magic of Tidying Up","author":"Marie Kondo","price":9.69},
	{"id":3,"name":"Refactoring: Improving the Design of Existing Code","author":"Martin Fowler","price":47.99}
]

Если логин неверный!

401
{
	"timestamp":"2019-10-09T07:06:57.966+0000",
	"status":401,
	"error":"Unauthorized",
	"message":"Unauthorized",
	"path":"/books"
}

2. Упреждающая Базовая Аутентификация

Эта упреждающая базовая аутентификация снизит накладные расходы на установление соединения, прочитайте это Аутентификация HttpClient

package com.mkyong.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientAuth2 {

    public static void main(String[] args) throws IOException {

        HttpGet request = new HttpGet("http://localhost:8080/books");

        HttpHost target = new HttpHost("localhost", 8080, "http");
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(
                new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials("user", "password")
        );

        AuthCache authCache = new BasicAuthCache();
        authCache.put(target, new BasicScheme());

        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        try (CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(provider)
                .build();
             CloseableHttpResponse response = httpClient.execute(target, request, localContext)) {

            // 401 if wrong user/password
            System.out.println(response.getStatusLine().getStatusCode());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // return it as a String
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            }

        }

    }

}

Рекомендации

Оригинал: “https://mkyong.com/java/apache-httpclient-basic-authentication-examples/”