Java 中是否有用于解析 url 查询参数的等效库?
为了说明我想要什么,我发送一个代码示例:
use URI;
use URI::QueryParam;
$u = URI->new("http://www.google.com?a=b&c=d");
print $u->query,"\n"; # prints foo=1&foo=2&foo=3
for my $key ($u->query_param) {
print "$key: ", join(", ", $u->query_param($key)), "\n";
}
输出为:
a=b&c=d
a: b
c: d
我不喜欢编写自己的查询片段解析函数。
最佳答案
不完全是这样,但接近:
final URI uri = URI.create(inputString);
final String[] queryParams = uri.getQuery().split("&");
然后,您将再次拆分 "="
queryParams
的每个元素。
注意:不要直接使用 URLDecoder
来解码查询片段的值;它将把 +
变成空格,which is wrong according to the URI spec (pchar
包含 sub-delim
包含 +
!)
一个可行的解决方案是:
URLDecoder.decode(param.replace("+", "%2b"), "UTF-8")
要进行编码,请使用 Guava 的 UrlPathSegmentEscaper
。
演示:这个简单的主要:
public static void main(final String... args)
throws UnsupportedEncodingException, URISyntaxException
{
System.out.println(URLDecoder.decode("a+b", "UTF-8"));
System.out.println(new URI("http", "foo.bar", "/baz", "op=a+b", null));
System.out.println(new URI("http", "foo.bar", "/baz", "op=a b", null));
}
打印:
a b // WRONG!
http://foo.bar/baz?op=a+b
http://foo.bar/baz?op=a%20b
关于java 相当于 perl URI::QueryParam 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23535012/