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

前端 未结 7 824
没有蜡笔的小新
没有蜡笔的小新 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:12

    If your server is running behind a proxy server, make sure your proxy header is set:

    proxy_set_header X-Forwarded-Proto  $scheme;
    

    Then to get the right scheme & url you can use springframework's classes:

    public String getUrl(HttpServletRequest request) {
        HttpRequest httpRequest = new ServletServerHttpRequest(request);
        UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();
    
        String scheme = uriComponents.getScheme();             // http / https
        String serverName = request.getServerName();     // hostname.com
        int serverPort = request.getServerPort();        // 80
        String contextPath = request.getContextPath();   // /app
    
        // Reconstruct original requesting URL
        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://");
        url.append(serverName);
    
        if (serverPort != 80 && serverPort != 443) {
            url.append(":").append(serverPort);
        }
        url.append(contextPath);
        return url.toString();
    }
    

提交回复
热议问题