请求中获取带有端口的主机名

请求中获取带有端口的主机名

本文介绍了如何从 http 或 https 请求中获取带有端口的主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个应用程序部署在一个 JBoss 容器(同一个 unix 盒子)中.如果我收到来自 app1 的请求,我需要为 app2 发送相应的请求.

I have two applications deployed in a JBoss container (same unix box). If I receive a request from app1, I need to send a corresponding request for app2.

示例:如果 app1 请求:http://example.com/context?param1=123,然后我需要提取 http://example.com/,以便我可以发送第二个应用的请求.

An Example: If app1 requests: http://example.com/context?param1=123,then I need to extract http://example.com/, so that I can send the request for the second app.

我尝试过使用

  HttpServletRequest.getServerName() &
  HttpServletRequest.getServerPort() &
  HttpServletRequest.getHeader("host")

但我如何区分 httphttps?

but how can I destinguish between http or https?

推荐答案

您可以使用 HttpServletRequest.getScheme() 来检索http".或https".

You can use HttpServletRequest.getScheme() to retrieve either "http" or "https".

将它与 HttpServletRequest.getServerName() 一起使用应该足以重建您需要的 URL 部分.

Using it along with HttpServletRequest.getServerName() should be enough to rebuild the portion of the URL you need.

如果您使用标准端口(http 为 80,https 为 443),则无需在 URL 中明确放置端口.

You don't need to explicitly put the port in the URL if you're using the standard ones (80 for http and 443 for https).

编辑:如果您的 servlet 容器位于终止 SSL 的反向代理或负载平衡器之后,则有点棘手,因为请求将作为纯 http 转发到 servlet 容器.您有几个选择:

Edit: If your servlet container is behind a reverse proxy or load balancer that terminates the SSL, it's a bit trickier because the requests are forwarded to the servlet container as plain http. You have a few options:

  1. 使用 HttpServletRequest.getHeader("x-forwarded-proto") 代替;这仅在您的负载均衡器正确设置标头时才有效(Apache 应该 afaik).

  1. Use HttpServletRequest.getHeader("x-forwarded-proto") instead; this only works if your load balancer sets the header correctly (Apache should afaik).

在中配置 RemoteIpValveJBoss/Tomcat 将使 getScheme() 按预期工作.同样,这仅在负载平衡器设置正确的标头时才有效.

Configure a RemoteIpValve in JBoss/Tomcat that will make getScheme() work as expected. Again, this will only work if the load balancer sets the correct headers.

如果上述方法不起作用,您可以在 Tomcat/JBoss 中配置两个不同的连接器,一个用于 http,一个用于 https,如 这篇文章.

If the above don't work, you could configure two different connectors in Tomcat/JBoss, one for http and one for https, as described in this article.

这篇关于如何从 http 或 https 请求中获取带有端口的主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 05:45