I'd like to append key-value pair as a query parameter to an existing URL. While I could do this by checking for the existence of whether the URL has a query part or a fragment part and doing the append by jumping though a bunch of if-clauses but I was wondering if there was clean way if doing this through the Apache Commons libraries or something equivalent.
http://example.com
would be http://example.com?name=John
http://example.com#fragment
would be http://example.com?name=John#fragment
http://[email protected]
would be http://[email protected]&name=John
http://[email protected]#fragment
would be http://[email protected]&name=John#fragment
I've run this scenario many times before and I'd like to do this without breaking the URL in any way.
Simply use: echo http_build_url($url, array("query" => "the=query&parts=here"), HTTP_URL_JOIN_QUERY); .
There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started:
import javax.ws.rs.core.UriBuilder; ... return UriBuilder.fromUri(url).queryParam(key, value).build();
import org.apache.http.client.utils.URIBuilder; ... return new URIBuilder(url).addParameter(key, value).build();
import org.springframework.web.util.UriComponentsBuilder; ... return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
See also: GIST > URI Builder Tests
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With