I'm developing a Spring Boot application behind a Proxy server. Now I need to connect to an external API but I didn't figure out yet what to configure in order to enable the application to connect to the outside API, I already tried to pass the proxy data with the program arguments and I already tried to configure the proxy in the Java Control Panel. How do I get the application to use the proxy in order to access the API?
You can use your custom RestTemplate, here in an exemple :
YourCustomRestTemplate.java :
class YourCustomRestTemplate implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
HttpHost proxy = new HttpHost(PROXY_SERVER_HOST, PROXY_SERVER_PORT);
HttpClient httpClient = HttpClientBuilder.create()
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
@Override
public HttpHost determineProxy(HttpHost target, HttpRequest request, HttpContext context) throws HttpException {
return super.determineProxy(target, request, context);
}
})
.build();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}
}
When you want to build RestTemplate object to call the API :
RestTemplate restTemplate = new RestTemplateBuilder(new YourCustomRestTemplate()).build();
ResponseEntity<String> responseEntity = restTemplate.getForEntity("__URL__/get", String.class);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.