3

Usually Java comes along with a large set of sensible constants to use. HTTP and HTTPS default port numbers as assigned by IANA (80 and 443) would be sensible constants. I checked the javadoc of java.net.URL, java.net.HttpURLConnection and javax.net.ssl.HttpsURLConnection but didn’t find them there. Are those constants somewhere in the JavaSE? If not, are they somewhere available in the classes a web application on Tomcat has access to, e.g. org.apace.catalina or coyote? Just because I don’t like magic numbers in my code…

Do I have to do this in URL composition?

if(port != new URL("http://example.com/").getDefaultPort() &&
        port != new URL("https://example.com/").getDefaultPort()){
    stringBuilder.append(":");
    stringBuilder.append(port);
}
Matthias Ronge
  • 9,403
  • 7
  • 47
  • 63
  • See: http://stackoverflow.com/questions/13498275/are-http-and-https-default-port-numbers-defined-in-the-jdk I don't think there are standard defined constants in java for port numbers. – Bryan Abrams Jul 17 '13 at 06:51
  • Just insert the port number every time – fge Jul 17 '13 at 06:55
  • 2
    Also, don't use a `StringBuilder` to build URLs, use the `URI` class. It can do the job of encoding for you. And it has many constructors, including one taking a host/port number – fge Jul 17 '13 at 06:59
  • In the case of HTTP(S) ports, I don't think anyone has a problem with magic numbers. Declare them as constants and i don't see a problem. These numbers are not gonna change without the internet being rebuilt. – f1sh Jul 17 '13 at 07:01
  • @fge: Thanks for the `URI`. Not really nice yet but really much better: `String url = new URI(port == 443 ? "https" : "http", null, host, (port == 80 || port == 443) ? -1 : port, (path != null && path.length() > 0) ? path : "/", null, null).toString();` ☺ – Matthias Ronge Jul 17 '13 at 11:09

1 Answers1

5

Apache HttpClient has them, if this is a library you use:

Thilo
  • 257,207
  • 101
  • 511
  • 656