Snippets: Java: Spring: URL Building

20th August 2020 at 2:19pm
Snippets: Java: Spring
Map<String, String> uriParams = new HashMap<>();
uriParams.put("ip", "127.0.0.1");
uriParams.put("port", "8080");
uriParams.put("serviceName", "producer");

MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
queryParams.add("instanceId", "ins-1");
queryParams.add("token", "t1);

String urlTemplate = "http://{ip}:{port}/rate/{serviceName}?instanceId={instanceId}&token={token}";

// Build and expand handles escaping
String url = UriComponentsBuilder.fromUriString(urlTemplate).
        queryParams(queryParams).buildAndExpand(uriParams).toUriString();

// Resulting "http://127.0.0.1:8080/rate/producer?instanceId=ins-1&token=t1"