删除所有网址参数

时间:2017-08-31 04:33:13

标签: java url

我有一段代码可以从网址中删除选择性参数

    public String stripAndApplyTags(final List<NameValuePair> tags, final String url) throws URISyntaxException {
    final URIBuilder existingLinkUrl = new URIBuilder(url);
    List<NameValuePair> existingTags = existingLinkUrl.getQueryParams();
    List<NameValuePair> newTags = new ArrayList<>();

    for (Iterator<NameValuePair> queryParameterItr = existingTags.iterator(); queryParameterItr.hasNext();) {
        NameValuePair queryParameter = queryParameterItr.next();
        if (!queryParameter.getName().equals("test")) {
            newTags.add(queryParameter);
        }
    }
    newTags.addAll(tags);
    return existingLinkUrl.clearParameters().setParameters(newTags).build().toString();
}

但问题是我的网址是否为 -

https://somexyzz/test=s9u_simh_gw_i1?ie=UTF8

我有办法使用URIBuilder移除这个额外的测试标签吗?

2 个答案:

答案 0 :(得分:1)

  

有没有办法让我删除这个额外的测试标签   URIBuilder?

是的,您可以创建URL对象并获取所需信息:

public static void main(String[] args) throws ParseException, MalformedURLException {
    String foo = "https://somexyzz/test=s9u_simh_gw_i1?ie=UTF8";
    URL myUrl = new URL(foo);
    System.out.println("protocol = " + myUrl.getProtocol());
    System.out.println("authority = " + myUrl.getAuthority());
    System.out.println("host = " + myUrl.getHost());
    System.out.println("port = " + myUrl.getPort());
    System.out.println("path = " + myUrl.getPath());
    System.out.println("query = " + myUrl.getQuery());
    System.out.println("filename = " + myUrl.getFile());
    System.out.println("ref = " + myUrl.getRef());
}

答案 1 :(得分:0)

这将从您的网址

中删除所有queryParams
URIBuilder b = new URIBuilder(url);
b.removeQuery();