我需要使用受 OAuth2 保护的 API。为此,我正在使用 OAuth2RestTemplate。但我得到以下错误:
java.net.ConnectException: Connection timed out: connect
这是由于代理问题而发生的。我知道如何在 RestTemplate 中设置代理:
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("Proxy host", 8080));
clientHttpRequestFactory.setProxy(代理); RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
我尝试为OAuth2RestTemplate设置相同的方式:
@Bean
public OAuth2RestOperations restTemplate(OAuth2ClientContext oauth2ClientContext) {
OAuth2RestTemplate client = new OAuth2RestTemplate(resource(), oauth2ClientContext);
SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
clientHttpRequestFactory.setProxy(proxy);
client.setRequestFactory(clientHttpRequestFactory);
return client;
}
但它不起作用并给出“连接超时”异常。这是因为第一行OAuth2RestTemplate client = new OAuth2RestTemplate(resource(), oauth2ClientContext);
试图获取访问令牌,这意味着它也需要代理设置。如果我添加以下行,那么它可以工作:
System.setProperty("https.proxyHost", "urproxy.com");
System.setProperty("https.proxyPort", "8080");
但是我不能使用 System.setProperties("","") 选项,因为我们没有在 tomcat 服务器上设置的权限。
我进行了研究,但在创建此对象时找不到在 OAuth2RestTemplate 中设置代理的任何方法。
任何帮助,将不胜感激。谢谢