Java:仅主机,方案的字符串表示形式,可能是servlet请求的端口 [英] Java: String representation of just the host, scheme, possibly port from servlet request

查看:48
本文介绍了Java:仅主机,方案的字符串表示形式,可能是servlet请求的端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用不同的服务器和配置.获取scheme://host:[如果不是端口80,则为端口]的最佳Java代码方法是什么.

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 ==请求

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

基本上,我需要查询字符串和上下文"以外的所有内容.

Basically, I need everything but the query string and 'context'.

我还考虑过使用URL:

I was also consider using URL:

String absURL = request.getRequestURL();
URL url = new URL(absURL);

url.get????

推荐答案

尝试一下:

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

编辑

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

这篇关于Java:仅主机,方案的字符串表示形式,可能是servlet请求的端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆