Java URL encoding of query string parameters

前端 未结 12 1048
清歌不尽
清歌不尽 2020-11-21 05:27

Say I have a URL

http://example.com/query?q=

and I have a query entered by the user such as:

random word £500 bank

12条回答
  •  Happy的楠姐
    2020-11-21 06:12

    Here's a method you can use in your code to convert a url string and map of parameters to a valid encoded url string containing the query parameters.

    String addQueryStringToUrlString(String url, final Map parameters) throws UnsupportedEncodingException {
        if (parameters == null) {
            return url;
        }
    
        for (Map.Entry parameter : parameters.entrySet()) {
    
            final String encodedKey = URLEncoder.encode(parameter.getKey().toString(), "UTF-8");
            final String encodedValue = URLEncoder.encode(parameter.getValue().toString(), "UTF-8");
    
            if (!url.contains("?")) {
                url += "?" + encodedKey + "=" + encodedValue;
            } else {
                url += "&" + encodedKey + "=" + encodedValue;
            }
        }
    
        return url;
    }
    

提交回复
热议问题