Search code examples
javaspringurlresttemplate

How to create URL containing variables using Rest Template?


I don't know how to create URL. I want to get the value of city from User via form. AppID and app.myserviceWeatherUrl I fetch from application.yml. How to connect URL to obtain something like this: app.myserviceWeatherUrl?q=city&app.APPID ?

@Service
public class WeatherClient {

@Value("{app.APPID}")
private String appID;
@Value("{app.myserviceWeatherUrl}")
private String baseUrl;

private final RestTemplate restTemplate;


public WeatherClient(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
}

public WeatherDto getWeather(String city) {
    try {
        return restTemplate.getForObject(baseUrl + city + appID, WeatherDto.class);
    } catch (Exception e) {
        throw new DataNotAvailableException();
    }
  }
}

Solution

  • You can try it like this:

     import java.net.URI;
     import org.springframework.web.util.UriComponentsBuilder;
    
    
     URI uri = UriComponentsBuilder.fromUriString(baseUrl)
                    .queryParam("city", city)
                    .queryParam("appId", appId)
                    .build().toUri();
    

    So, if baseUrl='/v1/api', city='Bern' and appId='4' it will be:

    /v1/api?city=Bern&appId=4
    

    And then pass uri to getForObject() method:

    restTemplate.getForObject(uri, WeatherDto.class);