如何使spring引导连接到外部api

yuvru6vn  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(390)

我正在代理服务器后面开发一个spring引导应用程序。现在我需要连接到外部api,但我还没有弄清楚要配置什么才能使应用程序连接到外部api,我已经尝试用程序参数传递代理数据,并且已经尝试在java控制面板中配置代理。如何让应用程序使用代理来访问api?

fnvucqvd

fnvucqvd1#

您可以使用自定义resttemplate,示例如下:
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));
    }
}

当您要构建resttemplate对象以调用api时:

RestTemplate restTemplate = new RestTemplateBuilder(new YourCustomRestTemplate()).build();

ResponseEntity<String> responseEntity = restTemplate.getForEntity("__URL__/get", String.class);

相关问题