Java URL encoding of query string parameters

前端 未结 12 994
清歌不尽
清歌不尽 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 06:12

    In my case i just needed to pass the whole url and encode only the value of each parameters. I didn't find a common code to do that so (!!) so i created this small method to do the job :

    public static String encodeUrl(String url) throws Exception {
        if (url == null || !url.contains("?")) {
            return url;
        }
    
        List list = new ArrayList<>();
        String rootUrl = url.split("\\?")[0] + "?";
        String paramsUrl = url.replace(rootUrl, "");
        List paramsUrlList = Arrays.asList(paramsUrl.split("&"));
        for (String param : paramsUrlList) {
            if (param.contains("=")) {
                String key = param.split("=")[0];
                String value = param.replace(key + "=", "");
                list.add(key + "=" +  URLEncoder.encode(value, "UTF-8"));
            }
            else {
                list.add(param);
            }
        }
    
        return rootUrl + StringUtils.join(list, "&");
    }
    
    public static String decodeUrl(String url) throws Exception {
        return URLDecoder.decode(url, "UTF-8");
    }
    

    It uses org.apache.commons.lang3.StringUtils

提交回复
热议问题