I have object of java.net.URI
type and I want to convert it to String
representation, but I'm interested only in the following components:
I don't want to have any other elements like query, fragment, user-info or scheme.
Doing it manually by getHost()
, getPort()
and getPath()
looks like a fragile solution. Is there any URI
formatter or customized toString
available?
By fragile here I mean that there might be some corner-cases that I could forget to handle manually. Like e.g. the case when host is IPv6 address and then it needs to have brackets.
You could fairly easily build a new URI:
URI partial = new URI(
null, // scheme
null, // user info
uri.getHost(),
uri.getPort(),
uri.getPath(),
null, // query
null); // fragment
String text = partial.toString();
You'd probably want to validate that the host is non-null in order for it to be sensible though.
Alternatively, the concatenation approach is really unlikely to be much more complicated - and I assume you'll have unit tests to check all combinations whatever the implementation.
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