【问题标题】:UriComponents returns IP instead of domainUriComponents 返回 IP 而不是域
【发布时间】:2018-11-21 11:16:00
【问题描述】:

我在网络技术方面很薄弱,也许你可以帮助我。我有一个简单的代码

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();
    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString()).build();
    UriComponents newUriComponents = UriComponentsBuilder.newInstance().scheme(uriComponents.getScheme())
            .host(uriComponents.getHost()).port(uriComponents.getPort()).build();

    return newUriComponents.toUriString() + request.getContextPath();

此代码应返回具有特定路径的我的服务器的链接。问题是 - 在产品服务器上 uriComponents.getHost() 返回 IP 而不是域名。当我通过浏览器访问服务器时,域工作。我可以去 http://exmaple.com/some/one/path 并希望得到答案(在 JSON 中,没有重定向。只需获取请求和 json 答案) - http://exmaple.com/some/another/path 但我显示的代码返回 - http://78.54.128.98.com/some/another/path (IP 地址只是示例)。所以我不知道为什么我的代码返回 IP 而不是域名。只有我能说的更多 - 在我的本地机器上我没有任何问题。代码返回 localhost,或者如果我将 127.0.0.1 exmaple.com 添加到主机文件,我的代码将返回正确的 exmaple.com,没有任何 ip

【问题讨论】:

    标签: java spring networking dns


    【解决方案1】:

    这不是URIComponents 的问题,它会解析输入的内容。更具体的看UriComponentsBuilder.fromHttpUrl的来源你看:

    public static UriComponentsBuilder fromHttpUrl(String httpUrl) {
        Assert.notNull(httpUrl, "HTTP URL must not be null");
        Matcher matcher = HTTP_URL_PATTERN.matcher(httpUrl);
        if (matcher.matches()) {
            UriComponentsBuilder builder = new UriComponentsBuilder();
            String scheme = matcher.group(1);
            builder.scheme(scheme != null ? scheme.toLowerCase() : null);
            builder.userInfo(matcher.group(4));
            String host = matcher.group(5);
            if (StringUtils.hasLength(scheme) && !StringUtils.hasLength(host)) {
                throw new IllegalArgumentException("[" + httpUrl + "] is not a valid HTTP URL");
            }
            builder.host(host);
            String port = matcher.group(7);
            if (StringUtils.hasLength(port)) {
                builder.port(port);
            }
            builder.path(matcher.group(8));
            builder.query(matcher.group(10));
            return builder;
        }
        else {
            throw new IllegalArgumentException("[" + httpUrl + "] is not a valid HTTP URL");
        }
    }
    

    您可以注意到,模式匹配器是在 url 的预期结构上定义的,并且部分是根据匹配器解析的。如果您看到IP,则表示输入中指定的url (request.getRequestURL().toString()) 包含IP 地址作为主机。

    这意味着您应该在链中寻找上述有罪的人,从调用这段代码的人开始,并跟踪链接,直到找到原因。

    【讨论】:

      猜你喜欢
      • 2015-07-17
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      相关资源
      最近更新 更多