【问题标题】:How to enable Spring Boot to connect to external API如何使 Spring Boot 连接到外部 API
【发布时间】:2021-09-17 19:49:42
【问题描述】:

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

【问题讨论】:

  • 你可以使用RestTemplate调用外部api并从api读取json
  • 为此使用 spring rest 模板或 web 客户端。

标签: java spring-boot networking proxy spring-boot-configuration


【解决方案1】:

你可以使用你的自定义 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 2021-07-16
    • 1970-01-01
    • 2018-02-02
    • 2019-03-05
    • 2011-07-10
    • 2019-02-13
    • 2018-08-19
    相关资源
    最近更新 更多