gpt4 book ai didi

java - 如何使用 Java 从相对 URL 构建绝对 URL?

转载 作者:可可西里 更新时间:2023-11-01 16:26:18 25 4
gpt4 key购买 nike

我有一个相对的 url 字符串,知道主机和协议(protocol)。如何构建绝对 url 字符串?

看起来很简单?乍一看是的,但直到逃脱的角色出现。我必须从 302 代码 http(s) 响应位置 header 构建绝对 url。

让我们考虑一个例子

protocol: http
host: example.com
location: /path/path?param1=param1Data&param2= "

首先,我尝试像这样构建 url 字符串:

Sting urlString = protocol+host+location

URL 类的构造函数不转义空格和双引号:

new URL(urlString)

URI 类的构造函数因异常而失败:

new URI(urlString)

URI.resolve 方法也因异常而失败

然后我发现 URI 可以转义查询字符串中的参数,但只有少数构造函数,例如:

URI uri = new URI("http", "example.com", 
"/path/path", "param1=param1Data&param2= \"", null);

此构造函数需要路径和查询作为单独的参数,但我有一个相对 URL,并且它没有按路径和查询部分拆分。

我可以考虑检查相对 URL 是否包含“?”问号并认为它之前的所有内容都是路径,之后的所有内容都是查询,但是如果相对 url 不包含路径,而是仅查询,并且查询包含“?”怎么办?符号?那么这将不起作用,因为查询的一部分将被视为路径。

现在我不知道如何从相对 url 构建绝对 url。

这些公认的答案似乎是错误的:

当相对于包含主机和某些路径部分的 url 给出相对 url 时,考虑这种情况可能会很好:

初始网址 http://example.com/...some小路...relative/home?...在这里查询...

获得 java 核心解决方案会很棒,尽管仍然可以使用一个好的库。

最佳答案

第一个?表示查询字符串开始的位置:

3.4. Query

[...] The query component is indicated by the first question mark (?) character and terminated by a number sign (#) character or by the end of the URI.

一种简单的方法(不处理片段并假定查询字符串始终存在)如下所示:

String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2";

String path = location.substring(0, location.indexOf("?"));
String query = location.substring(location.indexOf("?") + 1);

URI uri = new URI(protocol, host, path, query, null);

也可以处理片段的更好方法可能是:

String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2#fragment";

// Split the location without removing the delimiters
String[] parts = location.split("(?=\\?)|(?=#)");

String path = null;
String query = null;
String fragment = null;

// Iterate over the parts to find path, query and fragment
for (String part : parts) {

// The query string starts with ?
if (part.startsWith("?")) {
query = part.substring(1);
continue;
}

// The fragment starts with #
if (part.startsWith("#")) {
fragment = part.substring(1);
continue;
}

// Path is what's left
path = part;
}

URI uri = new URI(protocol, host, path, query, fragment);

关于java - 如何使用 Java 从相对 URL 构建绝对 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com