How to convert map to url query string?

前端 未结 17 1539
盖世英雄少女心
盖世英雄少女心 2020-11-27 13:39

Do you know of any utility class/library, that can convert Map into URL-friendly query string?

Example:

I have a map:

\"param1\"=12,
\"param2         


        
17条回答
  •  北海茫月
    2020-11-27 14:20

    Update June 2016

    Felt compelled to add an answer having seen far too many SOF answers with dated or inadequate answers to very common problem - a good library and some solid example usage for both parse and format operations.

    Use org.apache.httpcomponents.httpclient library. The library contains this org.apache.http.client.utils.URLEncodedUtils class utility.

    For example, it is easy to download this dependency from Maven:

     
        org.apache.httpcomponents
        httpclient
        4.5
     
    

    For my purposes I only needed to parse (read from query string to name-value pairs) and format (read from name-value pairs to query string) query strings. However, there are equivalents for doing the same with a URI (see commented out line below).

    // Required imports

    import org.apache.http.NameValuePair;
    import org.apache.http.client.utils.URLEncodedUtils;
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.nio.charset.StandardCharsets;
    

    // code snippet

    public static void parseAndFormatExample() throws UnsupportedEncodingException {
            final String queryString = "nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk";
            System.out.println(queryString);
            // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk
    
            final List params =
                    URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
            // List params = URLEncodedUtils.parse(new URI(url), "UTF-8");
    
            for (final NameValuePair param : params) {
                System.out.println(param.getName() + " : " + param.getValue());
                // => nonce : 12345
                // => redirectCallbackUrl : http://www.bbc.co.uk
            }
    
            final String newQueryStringEncoded =
                    URLEncodedUtils.format(params, StandardCharsets.UTF_8);
    
    
            // decode when printing to screen
            final String newQueryStringDecoded =
                    URLDecoder.decode(newQueryStringEncoded, StandardCharsets.UTF_8.toString());
            System.out.println(newQueryStringDecoded);
            // => nonce=12345&redirectCallbackUrl=http://www.bbc.co.uk
        }
    

    This library did exactly what I needed and was able to replace some hacked custom code.

提交回复
热议问题