How to get host name with port from a http or https request

前端 未结 7 795
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 22:22

I have two applications deployed in jboss container(same unix box). If i get a request from app1, i need to frame a corresponding request for app2.

eg:

7条回答
  •  伪装坚强ぢ
    2020-12-02 23:05

    If you want the original URL just use the method as described by jthalborn. If you want to rebuild the url do like David Levesque explained, here is a code snippet for it:

    final javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) ...;
    final int serverPort = req.getServerPort();
    if ((serverPort == 80) || (serverPort == 443)) {
      // No need to add the server port for standard HTTP and HTTPS ports, the scheme will help determine it.
      url = String.format("%s://%s/...", req.getScheme(), req.getServerName(), ...);
    } else {
      url = String.format("%s://%s:%s...", req.getScheme(), req.getServerName(), serverPort, ...);
    }
    

    You still need to consider the case of a reverse-proxy:

    • request.getScheme() is returning http instead of returning https in java

    Could use constants for the ports but not sure if there is a reliable source for them, default ports:

    • Are HTTP and HTTPS default port numbers defined in the JDK?

    Most developers will know about port 80 and 443 anyways, so constants are not that helpful.

    Also see this similar post.

提交回复
热议问题