Java:仅主机、方案、可能来自 servlet 请求的端口的字符串表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1104611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: String representation of just the host, scheme, possibly port from servlet request
提问by Berlin Brown
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].
我使用不同的服务器和配置。获取 scheme://host:[port if it is not port 80] 的最佳 java 代码方法是什么。
Here is some code I have used, but don't know if this is the best approach. (this is pseudo code)
这是我使用过的一些代码,但不知道这是否是最好的方法。(这是伪代码)
HttpServletRequest == request
HttpServletRequest == 请求
String serverName = request.getServerName().toLowerCase();
String scheme = request.getScheme();
int port = request.getServerPort();
String val = scheme + "://" + serverName + ":" port;
Such that val returns:
这样 val 返回:
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:
我也考虑使用 URL:
String absURL = request.getRequestURL();
URL url = new URL(absURL);
url.get????
回答by dfa
try this:
试试这个:
URL serverURL = new URL(request.getScheme(), // http
request.getServerName(), // host
request.getServerPort(), // port
""); // file
EDIT
编辑
hiding default port on httpand https:
在http和https上隐藏默认端口:
int port = request.getServerPort();
if (request.getScheme().equals("http") && port == 80) {
port = -1;
} else if (request.getScheme().equals("https") && port == 443) {
port = -1;
}
URL serverURL = new URL(request.getScheme(), request.getServerName(), port, "");
回答by mcandre
回答by John Topley
public String getServer(HttpServletRequest request) {
int port = request.getServerPort();
StringBuilder result = new StringBuilder();
result.append(request.getScheme())
.append("://")
.append(request.getServerName());
if (port != 80) {
result.append(':')
.append(port);
}
return result;
}
回答by Rob H
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.
如果您想保留出现在请求中的 URL(例如,如果没有明确给出端口,则关闭端口),您可以使用类似这样的方法。正则表达式匹配 HTTP 和 HTTPS URL。捕获组 1 包含从方案到可选端口的服务器根。(这就是您想要的。)第 2 组仅包含主机名。
String regex = "(^http[s]?://([\w\-_]+(?:\.[\w\-_]+)*)(?:\:[\d]+)?).*$";
Matcher urlMatcher = Pattern.compile(regex).matcher(request.getRequestURL());
String serverRoot = urlMatcher.group(1);
回答by CookieOfFortune
I think java.net.URIdoes what you want.
我认为java.net.URI 可以满足您的需求。

