Запрос Java 11 HttpClient к HTTPS ресурсу через прокси
Необходимо выполнять REST запросы через прокси. В наличии несколько HTTP прокси-серверов, защищённых с помощью Basic Authentication. Используется Java 16.
Пример полностью работающего запроса при обращении к HTTP ресурсам:
var proxySettings = new ProxySettings("http", "proxy.ip.address", proxy.port, "userName", "password");
var request = HttpRequest.newBuilder(new URI("http://tv-games.ru")).build();
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(new InetSocketAddress(proxySettings.getUri(), proxySettings.port())))
.authenticator(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxySettings.userName(), proxySettings.getPasswordArray());
}
}).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Body: " + response.body());
System.out.println("Code: " + response.statusCode());
Это объект, несущий информацию о прокси-сервере:
public record ProxySettings(String scheme, String hostname, int port, String userName, String password) {
public char[] getPasswordArray() {
return password.toCharArray();
}
public String getUri() {
return scheme + "://" + hostname;
}
}
При запросе к HTTPS ресурсу, например, https://yandex.ru, я получаю ошибку 407 (Proxy Authentication Required).
В настоящее время я использую обходное решение на основе Apache HttpClient 5:
HttpHost targetHost = new HttpHost("https", "yandex.ru");
HttpHost proxyHost = new HttpHost(proxySettings.scheme(), proxySettings.hostname(), proxySettings.port());
//Create the HttpGet request object
HttpGet httpget = new HttpGet("/");
httpget.setConfig(RequestConfig.custom().setProxy(proxyHost).build());
//Create the CloseableHttpClient
CredentialsStore credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxySettings.hostname(), proxySettings.port()),
new UsernamePasswordCredentials(proxySettings.userName(), proxySettings.getPasswordArray()));
CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
//Get the result
CloseableHttpResponse closeableHttpResponse = client.execute(targetHost, httpget);
System.out.println("Body: " + EntityUtils.toString(closeableHttpResponse.getEntity()));
System.out.println("Code: " + httpResponse.code());
EntityUtils.consume(closeableHttpResponse.getEntity());
Однако, зависимости Apache HttpClient достаточно тяжёловесные, очень хочется остаться в рамках чистой Java.
Есть ли возможность силами встроенного HttpClient обращаться к HTTPS ресурсам через прокси?