@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配置类,配置主机、端口、用户名、密码