栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将查询参数附加到现有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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/573899.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号