Java URL encoding of query string parameters

前端 未结 12 989
清歌不尽
清歌不尽 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:07

    1. Use this: URLEncoder.encode(query, StandardCharsets.UTF_8.displayName()); or this:URLEncoder.encode(query, "UTF-8");
    2. You can use the follwing code.

      String encodedUrl1 = UriUtils.encodeQuery(query, "UTF-8");//not change 
      String encodedUrl2 = URLEncoder.encode(query, "UTF-8");//changed
      String encodedUrl3 = URLEncoder.encode(query, StandardCharsets.UTF_8.displayName());//changed
      
      System.out.println("url1 " + encodedUrl1 + "\n" + "url2=" + encodedUrl2 + "\n" + "url3=" + encodedUrl3);
      

提交回复
热议问题