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

后端 未结 7 1022
独厮守ぢ
独厮守ぢ 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 00:56

    There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started:


    Java EE 7

    import javax.ws.rs.core.UriBuilder;
    ...
    return UriBuilder.fromUri(url).queryParam(key, value).build();
    

    org.apache.httpcomponents:httpclient:4.5.2

    import org.apache.http.client.utils.URIBuilder;
    ...
    return new URIBuilder(url).addParameter(key, value).build();
    

    org.springframework:spring-web:4.2.5.RELEASE

    import org.springframework.web.util.UriComponentsBuilder;
    ...
    return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
    

    See also: GIST > URI Builder Tests

提交回复
热议问题