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

查看:1270
本文介绍了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天全站免登陆