Java URL encoding of query string parameters

前端 未结 12 992
清歌不尽
清歌不尽 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:08
    URL url= new URL("http://example.com/query?q=random word £500 bank $");
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), IDN.toASCII(url.getHost()), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
    String correctEncodedURL=uri.toASCIIString(); 
    System.out.println(correctEncodedURL);
    

    Prints

    http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$
    

    What is happening here?

    1. Split URL into structural parts. Use java.net.URL for it.

    2. Encode each structural part properly!

    3. Use IDN.toASCII(putDomainNameHere) to Punycode encode the host name!

    4. Use java.net.URI.toASCIIString() to percent-encode, NFC encoded unicode - (better would be NFKC!). For more info see: How to encode properly this URL

    In some cases it is advisable to check if the url is already encoded. Also replace '+' encoded spaces with '%20' encoded spaces.

    Here are some examples that will also work properly

    {
          "in" : "http://نامه‌ای.com/",
         "out" : "http://xn--mgba3gch31f.com/"
    },{
         "in" : "http://www.example.com/‥/foo",
         "out" : "http://www.example.com/%E2%80%A5/foo"
    },{
         "in" : "http://search.barnesandnoble.com/booksearch/first book.pdf", 
         "out" : "http://search.barnesandnoble.com/booksearch/first%20book.pdf"
    }, {
         "in" : "http://example.com/query?q=random word £500 bank $", 
         "out" : "http://example.com/query?q=random%20word%20%C2%A3500%20bank%20$"
    }
    

    The solution passes around 100 of the testcases provided by Web Plattform Tests.

    0 讨论(0)
  • 2020-11-21 06:08

    Using Spring's UriComponentsBuilder:

    UriComponentsBuilder
            .fromUriString(url)
            .build()
            .encode()
            .toUri()
    
    0 讨论(0)
  • 2020-11-21 06:11

    Guava 15 has now added a set of straightforward URL escapers.

    0 讨论(0)
  • 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<Object, Object> parameters) throws UnsupportedEncodingException {
        if (parameters == null) {
            return url;
        }
    
        for (Map.Entry<Object, Object> 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;
    }
    
    0 讨论(0)
  • 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<String> list = new ArrayList<>();
        String rootUrl = url.split("\\?")[0] + "?";
        String paramsUrl = url.replace(rootUrl, "");
        List<String> 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

    0 讨论(0)
  • 2020-11-21 06:16

    Apache Http Components library provides a neat option for building and encoding query params -

    With HttpComponents 4.x use - URLEncodedUtils

    For HttpClient 3.x use - EncodingUtil

    0 讨论(0)
提交回复
热议问题