How to get host name with port from a http or https request(如何从 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")
但我如何区分 http
或 https
?
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:
使用
HttpServletRequest.getHeader("x-forwarded-proto")
代替;这仅在您的负载均衡器正确设置标头时才有效(Apache 应该 afaik).
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 请求中获取带有端口的主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 http 或 https 请求中获取带有端口的主机名
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01