RestTemplate的JVM代理配置 - apache HttpClientBuilder

时间:2018-05-10 14:41:42

标签: java spring-boot proxy resttemplate jvm-arguments

我坚持使用这种代理配置。我正在使用RestTemplate,我需要为RestTemplate所做的所有调用应用代理。我正在尝试利用JVM参数,因为我真的需要代理我的本地开发盒。

代码:

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class RestTemplateProxy {

    public static void main(String...strings) {
        System.out.println(System.getProperties());
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(2000)
                .build();
        HttpClient defaultHttpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(poolingHttpClientConnectionManager)
                        .build();

        poolingHttpClientConnectionManager.setMaxTotal(200);
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(200);
        ClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(defaultHttpClient);

        RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);

        String res = restTemplate.getForObject("API URL.....", String.class);
        System.out.println(res);

    }

}

如何验证:

-Dhttp.proxyHost=localhost -Dhttps.proxyHost=localhost -Dhttp.proxyPort=1212 -Dhttps.proxyPort=1212

在非代理环境中,我使用代理主机到localhost - >它应该无法连接。相反,它绕过配置并尝试访问服务并获得响应。

系统参数打印:

https.proxyHost=localhost, http.proxyPort=1212, http.proxyHost=localhost, https.proxyPort=1212

1 个答案:

答案 0 :(得分:0)

要使Apache HttpClient使用使用VM args传递的代理设置,您必须在构建HTTP客户端时调用.useSystemProperties()

HttpClient defaultHttpClient = HttpClientBuilder.create()
.useSystemProperties()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(poolingHttpClientConnectionManager).build();