Java:仅表示主机、方案、可能来自 servlet 请求的端口的字符串表示形式
我使用不同的服务器和配置。 获取scheme://host:[port if it is not port 80]的最佳java代码方法是什么?
这是我使用过的一些代码,但不知道这是否是最好的方法。 (这是伪代码)
HttpServletRequest == request
String serverName = request.getServerName().toLowerCase();
String scheme = request.getScheme();
int port = request.getServerPort();
String val = scheme + "://" + serverName + ":" port;
这样 val 返回:
http(s)://server.com/
或者
http(s)://server.com:7770
基本上,我需要除查询字符串和“上下文”之外的所有内容。
我也考虑过使用 URL:
String absURL = request.getRequestURL();
URL url = new URL(absURL);
url.get????
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 have used, but don't know if this is the best approach.
(this is pseudo code)
HttpServletRequest == request
String serverName = request.getServerName().toLowerCase();
String scheme = request.getScheme();
int port = request.getServerPort();
String val = scheme + "://" + serverName + ":" port;
Such that val returns:
http(s)://server.com/
or
http(s)://server.com:7770
Basically, I need everything but the query string and 'context'.
I was also consider using URL:
String absURL = request.getRequestURL();
URL url = new URL(absURL);
url.get????
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个:
编辑
隐藏http和https上的默认端口:
try this:
EDIT
hiding default port on http and https:
正如 Cookie 所说,来自 java.net.URI (文档)。
As Cookie said, from java.net.URI (docs).
我认为 java.net.URI 做你想做的事。
I think java.net.URI does what you want.
如果您想保留请求中出现的 URL(例如,如果未明确给出则省略端口),您可以使用类似的内容。 正则表达式匹配 HTTP 和 HTTPS URL。 捕获组 1 包含从方案到可选端口的服务器根。 (这就是您想要的。)组 2 仅包含主机名。
If you want to preserve the URL as it appeared in the request (e.g. leaving off the port if it wasn't explicitly given), you can use something like this. The regex matches HTTP and HTTPS URLs. Capture group 1 contains the server root from the scheme to the optional port. (That's the one you want.) Group 2 contains the host name only.
不要使用 StringBuilder 或连接 URL 的各个部分,而是使用 org.springframework.web.servlet.support.ServletUriComponentsBuilder 类来形成 URL。 你可以做类似的事情,
请找到这个 文章解释了有效使用此类的几种方法。
Instead of using the StringBuilder, or concatenating parts of the URL, use the org.springframework.web.servlet.support.ServletUriComponentsBuilder class instead to form the URL. You could do something like
Please find this article explaining several ways to use this class effectively.