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://example.com?email=john.doe@email.com
would be http://example.com?email=john.doe@email.com&name=John
http://example.com?email=john.doe@email.com#fragment
would be http://example.com?email=john.doe@email.com&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.
Kotlin & clean, so you don't have to refactor before code review:
I suggest an improvement of the Adam's answer accepting HashMap as parameter
This can be done by using the java.net.URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax.
The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.
Output
Use the
URI
class.Create a new
URI
with your existingString
to "break it up" to parts, and instantiate another one to assemble the modified url: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
org.apache.httpcomponents:httpclient:4.5.2
org.springframework:spring-web:4.2.5.RELEASE
See also: GIST > URI Builder Tests