在 Spring boot Java 中将参数附加到现有 url?

Reh*_*hma 0 java api spring

我正在尝试调用rest api 并从api 获取数据。我需要在 Spring Boot 中向 url 添加动态参数。我有点迷失,不知道该怎么办。有人能给我建议吗?

RestTemplate restTemplate = new RestTemplate();
        String consumeJSONString = restTemplate.getForObject("https://maps.googleapis.com/maps/api/geocode/json?latlng=5.47686,-73.961452&key=YOUR_API_KEY"
, String.class);
Run Code Online (Sandbox Code Playgroud)

我想在 url 中动态附加 latlng 和 api 密钥。我真的很感激任何建议。

Job*_*eph 5

您必须使用以下getForObject方法变体

restTemplate.getForObject(url, responseType, uriVariables);
Run Code Online (Sandbox Code Playgroud)

于是就变成了..

String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng={latlng}&key={key}";

Map<String, Object> uriVariables = new HashMap<>();
uriVariables.put("latlng", "5.47686,-73.961452");
uriVariables.put("key", "YOUR_API_KEY");

String consumeJSONString =  restTemplate.getForObject(url, String.class, uriVariables);
Run Code Online (Sandbox Code Playgroud)