这可以通过使用java.net.URI类使用现有实例中的部分构造一个新实例来完成,这应确保它符合URI语法。
查询部分将为null或现有字符串,因此您可以决定用&附加另一个参数或开始新的查询。
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; } return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), newQuery, oldUri.getFragment()); } 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")); }}更短的选择
public static URI appendUri(String uri, String appendQuery) throws URISyntaxException { URI oldUri = new URI(uri); return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), oldUri.getQuery() == null ? appendQuery : oldUri.getQuery() + "&" + appendQuery, oldUri.getFragment());}输出量
http://example.com?name=Johnhttp://example.com?name=John#fragmenthttp://example.com?email=john.doe@email.com&name=Johnhttp://example.com?email=john.doe@email.com&name=John#fragment



