Spring RestTemplate 和代理身份验证 [英] Spring RestTemplate and Proxy Auth

查看:45
本文介绍了Spring RestTemplate 和代理身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Spring 进行 REST 调用.据我了解,正确的做法是使用 RestTemplate(?).问题是,我支持代理.

I'm trying to do REST calls with Spring. As I understand, the right way to go is using RestTemplate(?). Problem is, I'm behind a proxy.

这是我现在的代码:

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...

It seems to work, but I need to authenticate at the proxy, but how is this done? The Proxy type as well as the SimpleClientHttpRequestFactory type don't seem to handle credentials. Without credentials, I'm getting just 407...

推荐答案

经过相当多的不同选项后我决定了下面的代码,因为能够在创建时为 RestTemplate 设置代理,因此我可以将其重构为单独的方法.请注意,它还有一个额外的依赖项,因此请记住这一点.

After quite a few different options I settled on The below code due to the ability to set the proxy for the RestTemplate at creation so I could refactor it into a separate method. Just to note it also has an additional dependency so keep that in mind.

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 和代理身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆