feat: 代理IP增加用户名密码设置

This commit is contained in:
xiongxiaoyang 2025-03-14 18:36:14 +08:00
parent cdfe481d60
commit 74d7ea7000
3 changed files with 24 additions and 2 deletions

View File

@ -19,4 +19,8 @@ public class HttpProxyProperties {
private Integer port;
private String username;
private String password;
}

View File

@ -2,13 +2,18 @@ package com.java2nb.novel.core.utils;
import com.java2nb.novel.core.config.HttpProxyProperties;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
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.impl.client.HttpClients;
@ -61,6 +66,15 @@ public class RestTemplates {
if (Objects.nonNull(httpProxyProperties) && Boolean.TRUE.equals(httpProxyProperties.getEnabled())) {
HttpHost proxy = new HttpHost(httpProxyProperties.getIp(), httpProxyProperties.getPort());
clientBuilder.setProxy(proxy);
if (StringUtils.isNotBlank(httpProxyProperties.getUsername()) && StringUtils.isNotBlank(
httpProxyProperties.getPassword())) {
// 创建CredentialsProvider实例并添加代理认证信息
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
httpProxyProperties.getUsername(), httpProxyProperties.getPassword());
provider.setCredentials(AuthScope.ANY, credentials);
clientBuilder.setDefaultCredentialsProvider(provider);
}
}
CloseableHttpClient httpClient = clientBuilder.setConnectionManager(connectionManager)
.build();

View File

@ -78,6 +78,10 @@ http:
# 是否开启 HTTP 代理true-开启false-不开启
enabled: false
# 代理 IP
ip: u493.kdltps.com
ip: us.swiftproxy.net
# 代理端口号
port: 15818
port: 7878
# 代理用户名
username: swiftproxy_u
# 代理密码
password: swiftproxy_p