How can I append a query parameter to an existing URL?

后端 未结 7 989
独厮守ぢ
独厮守ぢ 2020-12-24 00:05

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 frag

相关标签:
7条回答
  • 2020-12-24 01:02

    Use the URI class.

    Create a new URI with your existing String to "break it up" to parts, and instantiate another one to assemble the modified url:

    URI u = new URI("http://example.com?email=john@email.com&name=John#fragment");
    
    // Modify the query: append your new parameter
    StringBuilder sb = new StringBuilder(u.getQuery() == null ? "" : u.getQuery());
    if (sb.length() > 0)
        sb.append('&');
    sb.append(URLEncoder.encode("paramName", "UTF-8"));
    sb.append('=');
    sb.append(URLEncoder.encode("paramValue", "UTF-8"));
    
    // Build the new url with the modified query:
    URI u2 = new URI(u.getScheme(), u.getAuthority(), u.getPath(),
        sb.toString(), u.getFragment());
    
    0 讨论(0)
提交回复
热议问题