user11230 user11230 - 1 month ago 11
Java Question

How to substitute a query parameter in a string url

Hello I have a url string like

http://example.com/foo/?bar=15&oof=myp


Now lets say that I want to change the int value in the bar parameter to 16, in order to have

http://example.com/foo/?bar=16&oof=myp


How can I do this? Considering that the number after the = might be of 1, 2 or ever 3 characters. Thank you

Answer

You can use UriComponentsBuilder like this:

String url = "http://example.com/foo/?bar=15&oof=myp";

UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromUriString(url);

urlBuilder.replaceQueryParam("bar", 107);

String result = urlBuilder.build().toUriString();

Substitute 107 with the number you want. With this method you can have URI or String object from urlBuilder.