Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert URI to String taking only host, port and path

Tags:

java

string

uri

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

like image 750
Michal Kordas Avatar asked Jan 06 '16 17:01

Michal Kordas


1 Answers

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.

like image 98
Jon Skeet Avatar answered Nov 14 '22 22:11

Jon Skeet