9

I have a URL as a String and I'm looking to perform various modifications to it. Specifically, I need to modify values in the query string if they already exist, and, if they don't, to create them.

It would seem to me that there should already be an existing class that I can construct with my URL as a String that would split the URL into its constituent components and allow me to modify each component individually. In the case of the query string, it should be possible to address it as a Map, modify it, then toString the URL object to get back the modified URL.

Java has a URL class but it seems extremely limited - they query string is treated as a String, not a Map, and the only way to modify it is to call set and specify all the components of the URL instead of just setting the component I want to set. Are there better alternatives out there? I'd prefer something within the standard java/javax packages, if possible, but I recognize that as unlikely.

1 Answer 1

7

There is no such JDK class that I know of.

Spring Web (Maven link) provides the UriComponentsBuilder class for building UriComponents which

Represents an immutable collection of URI components, mapping component type to string values. Contains convenience getters for all components. Effectively similar to java.net.URI, but with more powerful encoding options and support for URI template variables.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, UriComponentsBuilder looks a lot nicer than java.net.URI.
@KyleCronin You're welcome. You'll have to use the UriComponentsBuilder as an intermediary. I don't think you will find a mutable URI/URL class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.