1

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;
}
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
user2051552
  • 2,870
  • 1
  • 14
  • 7

2 Answers2

4

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

String urlNo80 = url80.replaceFirst(":\\d+", "");
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
4

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
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • 5
    *BEWARE*: Yes, this turns `http://www.somewhere.com:80/someplace` into `http://www.somewhere.com/someplace`, but it also turns `http://www.somewhere.com:1234/someplace` into `http://www.somewhere.com/someplace` which means this is a very dangerous solution in my opinion. – Peter V. Mørch Mar 02 '21 at 23:59