Java:仅表示主机、方案、可能来自 servlet 请求的端口的字符串表示形式

发布于 2024-07-26 08:12:23 字数 650 浏览 7 评论 0原文

我使用不同的服务器和配置。 获取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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

你好,陌生人 2024-08-02 08:12:23

试试这个:

URL serverURL = new URL(request.getScheme(),      // http
                        request.getServerName(),  // host
                        request.getServerPort(),  // port
                        "");                      // file

编辑

隐藏httphttps上的默认端口:

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, "");

try this:

URL serverURL = new URL(request.getScheme(),      // http
                        request.getServerName(),  // host
                        request.getServerPort(),  // port
                        "");                      // file

EDIT

hiding default port on http and 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, "");
始于初秋 2024-08-02 08:12:23
URI u=new URI("http://www.google.com/");
String s=u.getScheme()+"://"+u.getHost()+":"+u.getPort();

正如 Cookie 所说,来自 java.net.URI (文档)。

URI u=new URI("http://www.google.com/");
String s=u.getScheme()+"://"+u.getHost()+":"+u.getPort();

As Cookie said, from java.net.URI (docs).

浮云落日 2024-08-02 08:12:23
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;
}
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;
}
我的影子我的梦 2024-08-02 08:12:23

我认为 java.net.URI 做你想做的事。

I think java.net.URI does what you want.

心作怪 2024-08-02 08:12:23

如果您想保留请求中出现的 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);

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.

String regex = "(^http[s]?://([\\w\\-_]+(?:\\.[\\w\\-_]+)*)(?:\\:[\\d]+)?).*$";
Matcher urlMatcher = Pattern.compile(regex).matcher(request.getRequestURL());
String serverRoot = urlMatcher.group(1);
暗藏城府 2024-08-02 08:12:23

不要使用 StringBuilder 或连接 URL 的各个部分,而是使用 org.springframework.web.servlet.support.ServletUriComponentsBuilder 类来形成 URL。 你可以做类似的事情,

URL url = ServletUriComponentsBuilder.fromRequestUri(req).
                replacePath("/").build()
                .toUri().toURL();

请找到这个 文章解释了有效使用此类的几种方法。

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

URL url = ServletUriComponentsBuilder.fromRequestUri(req).
                replacePath("/").build()
                .toUri().toURL();

Please find this article explaining several ways to use this class effectively.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文