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

后端 未结 7 1026
独厮守ぢ
独厮守ぢ 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:58

    I suggest an improvement of the Adam's answer accepting HashMap as parameter

    /**
     * Append parameters to given url
     * @param url
     * @param parameters
     * @return new String url with given parameters
     * @throws URISyntaxException
     */
    public static String appendToUrl(String url, HashMap parameters) throws URISyntaxException
    {
        URI uri = new URI(url);
        String query = uri.getQuery();
    
        StringBuilder builder = new StringBuilder();
    
        if (query != null)
            builder.append(query);
    
        for (Map.Entry entry: parameters.entrySet())
        {
            String keyValueParam = entry.getKey() + "=" + entry.getValue();
            if (!builder.toString().isEmpty())
                builder.append("&");
    
            builder.append(keyValueParam);
        }
    
        URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
        return newUri.toString();
    }
    

提交回复
热议问题