曾彪彪的个人网站
首页
文章列表
>>
文章详情
ResTemplate代理设置
作者:
曾彪彪
日期:
2023-05-16 05:18:03
阅读(922)
分类:
Spring 家族
在使用RestTemplate时,如果需要设置代理,可以参考如下代码: ``` @Bean public RestTemplate restTemplate() { RestTemplate restTemplate; ProxyConfig proxyConfig = proxyConfig(); if (proxyConfig.isEnableProxy()) { final String username = proxyConfig.getUsername(); final String password = proxyConfig.getPassword(); final String proxyUrl = proxyConfig.getProxyUrl(); final int port = Integer.parseInt(proxyConfig.getProxyPort()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(proxyUrl, port), new UsernamePasswordCredentials(username, password)); HttpHost myProxy = new HttpHost(proxyUrl, port); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setProxy(myProxy).setDefaultCredentialsProvider(credentialsProvider).disableCookieManagement(); HttpClient httpClient = clientBuilder.build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(httpClient); restTemplate = new RestTemplate(factory); } else { restTemplate = new RestTemplate(); } RestTemplateUtil.setRestTemplateTimeout(restTemplate, 30000, 30000); restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8"))); return restTemplate; } ``` 在读取代理配置时,可以把配置写在配置文件中,但是这样不是很方便,比如无法灵活修改,也容易在配置文件中暴露代理信息。推荐的方法是通过jvm参数设置代理信息。读取代理信息代码如下: ``` @Bean public ProxyConfig proxyConfig() { ProxyConfig proxyConfig = new ProxyConfig(); Properties properties = System.getProperties(); String proxySet = properties.getProperty("proxySet"); if (proxySet != null && proxySet.toLowerCase().equals("true")) { proxyConfig.setEnableProxy(true); proxyConfig.setProxyUrl(properties.getProperty("http.proxyHost")); proxyConfig.setProxyPort(properties.getProperty("http.proxyPort")); proxyConfig.setUsername(properties.getProperty("http.proxyUser")); proxyConfig.setPassword(properties.getProperty("http.proxyPassword")); } return proxyConfig; } ``` 在启动应用时,添加如下参数即可。记得要添加proxySet=true参数。 ``` java -jar -DproxySet=true -Dhttp.proxyHost=proxyServer -Dhttp.proxyPort=8888 -Dhttp.proxyUser=username -Dhttp.proxyPassword=password -Dspring.profiles.active=test -Dsun.net.client.defaultConnectTimeout=30000 -Dsun.net.client.defaultReadTimeout=30000 application-0.0.1-SNAPSHOT.jar >/dev/null 2>&1 & ```
评论(0)
评论(必填)
名称(必填)
联系方式(可选)
验证码(必填)
提交
评论(必填)
名称(必填)
联系方式(可选)
验证码(必填)