Java URL encoding of query string parameters

前端 未结 12 1045
清歌不尽
清歌不尽 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 06:07

    You need to first create a URI like:

    String urlStr = "http://www.example.com/CEREC® Materials & Accessories/IPS Empress® CAD.pdf"
    URL url= new URL(urlStr);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
    

    Then convert that Uri to ASCII string:

    urlStr=uri.toASCIIString();
    

    Now your url string is completely encoded first we did simple url encoding and then we converted it to ASCII String to make sure no character outside US-ASCII are remaining in string. This is exactly how browsers do.

提交回复
热议问题