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

后端 未结 5 1779
天命终不由人
天命终不由人 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条回答
  •  猫巷女王i
    2021-01-04 22:57

    try this:

    URL serverURL = new URL(request.getScheme(),      // http
                            request.getServerName(),  // host
                            request.getServerPort(),  // port
                            "");                      // file
    

    EDIT

    hiding default port on http and https:

    int port = request.getServerPort();
    
    if (request.getScheme().equals("http") && port == 80) {
        port = -1;
    } else if (request.getScheme().equals("https") && port == 443) {
        port = -1;
    }
    
    URL serverURL = new URL(request.getScheme(), request.getServerName(), port, "");
    

提交回复
热议问题