user2051552
user2051552

Reputation: 3144

Remove port number from a url in java

I want to write a function in java which removes the port if it is the default port.

So if given

String url80 = "http://www.somewhere.com:80/someplace";

it will return

String urlNo80 = "http://www.somewhere.com/someplace";

And if given

String url443 = "https://www.somewhere.com:443/someplace";

It will return

String urlNo443 = "https://www.somewhere.com/someplace";

Is there a better way to do it than

public String removePortIfDefault(String inUrl) {
    String returnUrl = inUrl;
    if (inUrl.contains("http://") && inUrl.contains(":80")) {
        returnUrl = inUrl.replaceAll(":80", "");
    }
    if (inUrl.contains("https://") && inUrl.contains(":443")) {
        returnUrl = inUrl.replaceAll(":443", "");
    }
    return returnUrl;
}

Upvotes: 1

Views: 3967

Answers (2)

Andreas
Andreas

Reputation: 159096

Don't use string manipulation to work with a URL. Java has classes for that.

String url80 = "http://www.somewhere.com:80/someplace";
// Using java.net.URI
URI uri = URI.create(url80);
uri = new URI(uri.getScheme(), uri.getHost(), uri.getPath(), uri.getFragment());
String urlNo80 = uri.toString(); // http://www.somewhere.com/someplace
// Using java.net.URL
URL url = new URL(url80);
url = new URL(url.getProtocol(), url.getHost(), url.getFile());
String urlNo80 = url.toString(); // http://www.somewhere.com/someplace

Upvotes: 4

Joakim Danielson
Joakim Danielson

Reputation: 51945

You can use replaceFirst (or replaceAll) with a regular expression

String urlNo80 = url80.replaceFirst(":\\d+", "");

Upvotes: 3

Related Questions