Convert URI to String taking only host, port and path

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:

  • host
  • port
  • path

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 would forget to handle manually. Like e.g. the case when host is IPv6 address and then it needs to have brackets.

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow