Wednesday, 22 March 2023

Good Practice of Creating URI from String

It is generally recommended to use the java.net.URI class to create and manipulate URIs rather than constructing URIs directly from strings. This is because the URI class provides a higher level of abstraction and ensures that the resulting URI is valid and conforms to the URI syntax rules.The URI class provides constructors and methods to create and manipulate URIs, and it automatically handles any encoding and decoding that needs to be done. For example, if you want to create a URI from a string that contains special characters, you can use the URI(String) constructor as follows:

URI uri = new URI("http", "example.com", "/path with spaces", "query=string", "fragment");

This will create a URI with the following components:

http://example.com/path%20with%20spaces?query=string#fragment

Note that the path component, which contains spaces, is automatically encoded as %20.When creating a URI from user input, it is important to validate the input and ensure that it does not contain any invalid characters or sequences. This can be done using the java.net.URI.create(String) method, which will throw an IllegalArgumentException if the input string is not a valid URI.Overall, using the URI class provides a more robust and reliable way to create and manipulate URIs in Java.



No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...