如何将查询参数附加到现有URL? [英] How can I append a query parameter to an existing URL?
问题描述
我想将键值对作为查询参数附加到现有URL。虽然我可以通过检查URL是否有查询部分或片段部分来执行此操作,并通过跳过一堆if子句来执行追加,但我想知道如果通过Apache执行此操作是否有干净的方法Commons库或类似的东西。
I'd like to append key-value pair as a query parameter to an existing URL. While I could do this by checking for the existence of whether the URL has a query part or a fragment part and doing the append by jumping though a bunch of if-clauses but I was wondering if there was clean way if doing this through the Apache Commons libraries or something equivalent.
http://example.com
将是 http ://example.com?name = John
http://example.com#fragment
将 http://example.com?name=John#fragment
http://example.com?email=john.doe@email.com
将 http://example.com?email=john.doe@email .com& name = John
http://example.com?email=john.doe@email。 com#fragment
将是 http://example.com?email=john.doe@email.com&name=John#fragment
我之前已多次运行此场景,我想在不破坏URL的情况下执行此操作。
I've run this scenario many times before and I'd like to do this without breaking the URL in any way.
推荐答案
这可以通过使用 java.net来完成。 URI 类使用现有部分构造新实例,这应该确保它符合URI语法。
This can be done by using the java.net.URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax.
查询部分将为null或现有字符串,因此您可以决定使用&添加另一个参数。或者开始一个新的查询。
The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.
public class StackOverflow26177749 {
public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
URI oldUri = new URI(uri);
String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = appendQuery;
} else {
newQuery += "&" + appendQuery;
}
URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
return newUri;
}
public static void main(String[] args) throws Exception {
System.out.println(appendUri("http://example.com", "name=John"));
System.out.println(appendUri("http://example.com#fragment", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe@email.com", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe@email.com#fragment", "name=John"));
}
}
输出
http://example.com?name=John
http://example.com?name=John#fragment
http://example.com?email=john.doe@email.com&name=John
http://example.com?email=john.doe@email.com&name=John#fragment
这篇关于如何将查询参数附加到现有URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!