RestTempalte使用代理配置用户名密码

@Configuration
public class RestTemplateConfig {

    private static final String PROXY_SERVER_HOST = "proxy.*.com";
    private static final Integer PROXY_SERVER_PORT = 8080;
    private static final String PROXY_USER_NAME = "test";
    private static final String PROXY_PASSWORD = "test";


    @Bean
    public RestTemplate setProxy() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        httpClientBuilder.setSSLContext(sslContext);
        this.setProxy(restTemplate); //设置代理
        this.setCredsProvider(httpClientBuilder); //设置代理密码
        HttpClient httpClient = httpClientBuilder.build();

        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // httpClient连接配置
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        return  restTemplate;
    }


    public void setProxy(RestTemplate restTemplate) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_SERVER_HOST, PROXY_SERVER_PORT));
        requestFactory.setProxy(proxy);
        restTemplate.setRequestFactory(requestFactory);
    }

    public void setCredsProvider(HttpClientBuilder httpClientBuilder) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(PROXY_SERVER_HOST, PROXY_SERVER_PORT),
                new UsernamePasswordCredentials(PROXY_USER_NAME, PROXY_PASSWORD)
        );
        HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
        httpClientBuilder.setProxy(proxy).setDefaultCredentialsProvider(credsProvider).disableCookieManagement();

    }

}

添加restTemplate配置类,配置主机、端口、用户名、密码

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值