Java: String representation of just the host, scheme, possibly port from servlet request

后端 未结 5 1777
天命终不由人
天命终不由人 2021-01-04 22:08

I work with different servers and configurations. What is the best java code approach for getting the scheme://host:[port if it is not port 80].

Here is some code I

5条回答
  •  无人及你
    2021-01-04 23:09

    If you want to preserve the URL as it appeared in the request (e.g. leaving off the port if it wasn't explicitly given), you can use something like this. The regex matches HTTP and HTTPS URLs. Capture group 1 contains the server root from the scheme to the optional port. (That's the one you want.) Group 2 contains the host name only.

    String regex = "(^http[s]?://([\\w\\-_]+(?:\\.[\\w\\-_]+)*)(?:\\:[\\d]+)?).*$";
    Matcher urlMatcher = Pattern.compile(regex).matcher(request.getRequestURL());
    String serverRoot = urlMatcher.group(1);
    

提交回复
热议问题