Spring Boot应用HttpClient连接失败及代理配置咨询
解决Spring Boot应用请求外部URL连接失败的代理配置方案
从你提供的日志来看,你的Spring Boot应用在尝试连接https://pi-collector-dev.tr-corporate-nonprod.aws-int.thomsonreuters.com:443时反复出现连接重置(Connection reset),但Postman请求该URL能正常返回200,核心原因就是Postman配置了代理,而你的应用没有。下面提供几种在Spring Boot中配置代理的可行方案:
方案1:通过配置文件设置全局代理
如果你的应用使用的是默认的HTTP客户端(比如RestTemplate、Spring Cloud Feign等),可以直接在application.properties或application.yml中添加系统属性配置,让应用启动时自动加载代理:
application.properties 配置:
# HTTP代理配置 systemProperties.http.proxyHost=你的代理地址 systemProperties.http.proxyPort=你的代理端口 # HTTPS代理配置(通常和HTTP代理一致) systemProperties.https.proxyHost=你的代理地址 systemProperties.https.proxyPort=你的代理端口 # 如果代理需要用户名密码认证,添加以下配置 systemProperties.http.proxyUser=你的代理用户名 systemProperties.http.proxyPassword=你的代理密码 systemProperties.https.proxyUser=你的代理用户名 systemProperties.https.proxyPassword=你的代理密码
application.yml 配置:
systemProperties: http: proxyHost: 你的代理地址 proxyPort: 你的代理端口 proxyUser: 你的代理用户名 proxyPassword: 你的代理密码 https: proxyHost: 你的代理地址 proxyPort: 你的代理端口 proxyUser: 你的代理用户名 proxyPassword: 你的代理密码
方案2:为RestTemplate手动配置代理
如果你的应用自定义了RestTemplate,可以直接在RestTemplate的Bean中配置代理,这种方式更灵活,适合只需要给特定HTTP客户端设置代理的场景:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import java.net.InetSocketAddress; import java.net.Proxy; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); // 设置代理地址和端口 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("你的代理地址", 你的代理端口)); factory.setProxy(proxy); // 如果代理需要认证,添加以下代码 /* factory.setCredentialsProvider(authScope -> new org.apache.http.auth.UsernamePasswordCredentials("你的代理用户名", "你的代理密码") ); */ return new RestTemplate(factory); } }
方案3:通过JVM启动参数配置代理
你也可以在启动Spring Boot应用时,通过JVM参数直接指定代理,这种方式对所有HTTP客户端都生效:
java -jar 你的应用.jar \ -Dhttp.proxyHost=你的代理地址 \ -Dhttp.proxyPort=你的代理端口 \ -Dhttps.proxyHost=你的代理地址 \ -Dhttps.proxyPort=你的代理端口 \ # 代理需要认证的话添加以下参数 -Dhttp.proxyUser=你的代理用户名 \ -Dhttp.proxyPassword=你的代理密码 \ -Dhttps.proxyUser=你的代理用户名 \ -Dhttps.proxyPassword=你的代理密码
验证配置是否生效
配置完成后重启应用,再次发起请求,如果日志中不再出现Connection reset,且成功推送事件到目标地址,说明代理配置生效了。
内容的提问来源于stack exchange,提问作者Pranam Bhat
相关产品推荐
相关产品推荐

