如何将查询参数附加到现有URL?

如何将查询参数附加到现有URL?,第1张

如何将查询参数附加现有URL?

这可以通过使用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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5565140.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存