postforobject 设置代理_Spring RestTemplate和代理身份验证

小编典典

经过许多不同的选择之后,由于能够在创建时为RestTemplate设置代理,因此我可以选择以下代码,因此我可以将其重构为单独的方法。只是要注意,它还具有其他依赖性,因此请记住这一点。

private RestTemplate createRestTemplate() throws Exception {

final String username = "myusername";

final String password = "myPass";

final String proxyUrl = "proxy.nyc.bigtower.com";

final int port = 8080;

CredentialsProvider credsProvider = new BasicCredentialsProvider();

credsProvider.setCredentials(

new AuthScope(proxyUrl, port),

new UsernamePasswordCredentials(username, password)

);

HttpHost myProxy = new HttpHost(proxyUrl, port);

HttpClientBuilder clientBuilder = HttpClientBuilder.create();

clientBuilder.setProxy(myProxy).setDefaultCredentialsProvider(credsProvider).disableCookieManagement();

HttpClient httpClient = clientBuilder.build();

HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

factory.setHttpClient(httpClient);

return new RestTemplate(factory);

}

//我使用的依赖项

org.apache.httpcomponents

httpclient

4.5.2

org.springframework

spring-web

4.2.5.RELEASE

2020-06-01