Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

url

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.

like image 554
Mridang Agarwalla Avatar asked Oct 03 '14 10:10

Mridang Agarwalla


People also ask

Which HTTP method can append query string to URL?

Simply use: echo http_build_url($url, array("query" => "the=query&parts=here"), HTTP_URL_JOIN_QUERY); .


1 Answers

There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started:


Java EE 7

import javax.ws.rs.core.UriBuilder; ... return UriBuilder.fromUri(url).queryParam(key, value).build(); 

org.apache.httpcomponents:httpclient:4.5.2

import org.apache.http.client.utils.URIBuilder; ... return new URIBuilder(url).addParameter(key, value).build(); 

org.springframework:spring-web:4.2.5.RELEASE

import org.springframework.web.util.UriComponentsBuilder; ... return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri(); 

See also: GIST > URI Builder Tests

like image 193
Nick Grealy Avatar answered Oct 04 '22 12:10

Nick Grealy