Spring RestTemplate和代理身份验证

我正在尝试使用Spring进行REST调用。据我了解,正确的方法是使用RestTemplate(?)。问题是,我在代理后面。

这是我现在的代码:

SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();

InetSocketAddress address = new InetSocketAddress(host, 3128);

Proxy proxy = new Proxy(Proxy.Type.HTTP, address);

factory.setProxy(proxy);

RestTemplate restTemplate = new RestTemplate();

restTemplate.setRequestFactory(factory);

看来可行,但是我需要在代理处进行身份验证,但是如何完成呢?该Proxy类型以及该SimpleClientHttpRequestFactory类型似乎都不处理凭据。没有凭证,我只会得到407

回答:

经过许多不同的选择之后,由于能够在创建时为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);

}

//我使用的依赖项

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpclient</artifactId>

<version>4.5.2</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>4.2.5.RELEASE</version>

</dependency>

以上是 Spring RestTemplate和代理身份验证 的全部内容, 来源链接: utcz.com/qa/426204.html

回到顶部