Java - 在url中替换主机?

Bra*_*rks 11 java

在java中,我想Host用new 替换url 的一部分Host,其中host和url都是作为字符串提供的.

这应该考虑到主机可以在其中具有端口的事实,如RFC中定义的

例如,给出以下输入

我应该从正确执行此操作的函数中获取以下输出

有没有人知道Host在url中正确替换的任何库或例程?

编辑:对于我的用例,我希望我的主机替换匹配java servlet将响应的内容.我通过运行本地java Web服务器尝试了这一点,然后使用curl -H 'Host:superduper.com:80' 'http://localhost:8000/testurl'该端点进行测试,只需返回url request.getRequestURL().toString(),其中request是a HttpServletRequest.它返回了http://superduper.com/testurl,所以它删除了http的默认端口,所以这也是我正在努力的.

Mar*_*arc 8

Spring Framework提供了UriComponentsBuilder。您可以像这样使用它:

import org.springframework.web.util.UriComponentsBuilder;

String initialUri = "http://localhost/me/out?it=5";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(initialUri);
String modifiedUri = builder.host("myserver").port("20000").toUriString();
System.out.println(modifiedUri);
// ==> http://myserver:20000/me/out?it=5
Run Code Online (Sandbox Code Playgroud)

在这里,您需要在单独的调用中提供主机名和端口,以获取正确的编码。


VGR*_*VGR 5

您正确使用java.net.URI。主机和端口(以及用户/密码,如果存在的话)统称为URI 的授权组件:

public static String replaceHostInUrl(String originalURL,
                                      String newAuthority)
throws URISyntaxException {

    URI uri = new URI(originalURL);
    uri = new URI(uri.getScheme().toLowerCase(Locale.US), newAuthority,
        uri.getPath(), uri.getQuery(), uri.getFragment());

    return uri.toString();
}
Run Code Online (Sandbox Code Playgroud)

(URI的方案必须是小写的,因此虽然可以说上述代码不能完美地保留所有原始URL的非授权部分,但大写的方案从一开始就从来没有真正合法。而且,当然,不会影响网址连接的功能。)

请注意,您的某些测试有误。例如:

assertEquals("https://super/me/out?it=5", replaceHostInUrl("https://www.test.com:4300/me/out?it=5","super:443")); 
assertEquals("http://super/me/out?it=5", replaceHostInUrl("http://www.test.com:4300/me/out?it=5","super:80")); 
Run Code Online (Sandbox Code Playgroud)

尽管https://super/me/out?it=5在功能上与https://super:443/me/out?it=5(由于https的默认端口为443)相同,但是如果您在URI中指定了显式端口,则URI在其权限中具有指定的端口,因此应该保留该端口。

更新:

如果要删除显式但不必要的端口号,可以使用URL.getDefaultPort()进行检查:

public static String replaceHostInUrl(String originalURL,
                                      String newAuthority)
throws URISyntaxException,
       MalformedURLException {

    URI uri = new URI(originalURL);
    uri = new URI(uri.getScheme().toLowerCase(Locale.US), newAuthority,
        uri.getPath(), uri.getQuery(), uri.getFragment());

    int port = uri.getPort();
    if (port > 0 && port == uri.toURL().getDefaultPort()) {
        uri = new URI(uri.getScheme(), uri.getUserInfo(),
            uri.getHost(), -1, uri.getPath(),
            uri.getQuery(), uri.getFragment());
    }

    return uri.toString();
}
Run Code Online (Sandbox Code Playgroud)