Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute a query parameter in a string url

Tags:

java

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

like image 236
user11230 Avatar asked Oct 21 '16 13:10

user11230


People also ask

How can I append a query parameter to an existing URL?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

How do you write a valid URL for query string parameters?

A URL which contains a page on your site should NEVER have a "/" after it (e.g. "foo. html/") A URL should always have a single question mark in it "?" URL Query String parameters should be separated by the ampersand "&"


1 Answers

You can use UriComponentsBuilder (it's part of Spring Web jar) 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.

like image 164
amicoderozer Avatar answered Sep 28 '22 11:09

amicoderozer