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

后端 未结 5 1766
天命终不由人
天命终不由人 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:06

    public String getServer(HttpServletRequest request) {
      int port = request.getServerPort();
      StringBuilder result = new StringBuilder();
      result.append(request.getScheme())
            .append("://")
            .append(request.getServerName());
    
      if (port != 80) {
        result.append(':')
              .append(port);
      }
    
      return result;
    }
    

提交回复
热议问题