You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为特定HTTPS请求配置带指定代理的RestTemplate?

使用RestTemplate通过代理调用特定HTTPS端点

自定义带代理的RestTemplate Bean

为了仅让特定请求通过代理调用HTTPS端点,我单独创建了一个带有proxyRestTemplate限定符的RestTemplate Bean,代码如下:

@Bean
@Qualifier("proxyRestTemplate")
public RestTemplate proxyRestTemplate() {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

    // 为HTTPS请求设置SOCKS类型代理
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("proxyhost.com", 8080));
    requestFactory.setProxy(proxy);

    // 配置超时参数
    requestFactory.setConnectTimeout(5000); // 设置连接超时时间
    requestFactory.setReadTimeout(5000); // 设置读取超时时间

    // 创建RestTemplate并绑定请求工厂
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setRequestFactory(requestFactory);

    return restTemplate;
}

业务类中使用该RestTemplate

在业务类中使用这个带代理的RestTemplate调用返回CSV数据的目标HTTPS接口,代码如下:

RestTemplate proxyRestTemplate;

public Stream<Entry> get() {
    try {
        // 添加基础认证拦截器
        proxyRestTemplate.getInterceptors().add(
            new BasicAuthenticationInterceptor("user", "pass"));
        Stream<Entry> resultResponse =
            proxyRestTemplate.execute(
                "https://返回CSV的目标接口地址",
                HttpMethod.GET,
                null,
                clientHttpResponse -> {
                    InputStreamReader reader = new InputStreamReader(clientHttpResponse.getBody());
                    CsvToBean<Entry> csvToBean = new CsvToBeanBuilder<Entry>(reader)
                        .withType(Entry.class)
                        .withSeparator(',')
                        .withIgnoreLeadingWhiteSpace(true)
                        .build();
                    return csvToBean.stream();
                });   
    } catch (Exception e) {
        // 异常处理逻辑
        ....
    }
}

设计思路

我特意创建这个独立的RestTemplate实例,目的是让应用中其他所有接口请求都不经过代理,仅将此实例用于需要通过代理访问的特定HTTPS端点。

内容的提问来源于stack exchange,提问作者cUser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:00:14