Java URL encoding of query string parameters

前端 未结 12 993
清歌不尽
清歌不尽 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 05:54

    I would not use URLEncoder. Besides being incorrectly named (URLEncoder has nothing to do with URLs), inefficient (it uses a StringBuffer instead of Builder and does a couple of other things that are slow) Its also way too easy to screw it up.

    Instead I would use URIBuilder or Spring's org.springframework.web.util.UriUtils.encodeQuery or Commons Apache HttpClient. The reason being you have to escape the query parameters name (ie BalusC's answer q) differently than the parameter value.

    The only downside to the above (that I found out painfully) is that URL's are not a true subset of URI's.

    Sample code:

    import org.apache.http.client.utils.URIBuilder;
    
    URIBuilder ub = new URIBuilder("http://example.com/query");
    ub.addParameter("q", "random word £500 bank \$");
    String url = ub.toString();
    
    // Result: http://example.com/query?q=random+word+%C2%A3500+bank+%24
    

    Since I'm just linking to other answers I marked this as a community wiki. Feel free to edit.

提交回复
热议问题