可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:

问题:

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 $

I want the result to be a properly encoded URL:

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

What's the best way to achieve this? I tried URLEncoder and creating URI/URL objects but none of them come out quite right.

回答1:

URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.

String q = "random word £500 bank $";

String url = "http://example.com/query?q=" + URLEncoder.encode(q, "UTF-8");

Note that spaces in query parameters are represented by +, not %20, which is legitimately valid. The %20 is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?), not in query string (the part after ?).

Also note that there are two encode() methods. One without charset argument and another with. The one without charset argument is deprecated. Never use it and always specify the charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.

All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

See also:

回答2:

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.

回答3:

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.

回答4:

回答5:

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

回答6:

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 parameters) throws UnsupportedEncodingException {

if (parameters == null) {

return url;

}

for (Map.Entry 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;

}

回答7:

Use the following standard Java solution (passes around 100 of the testcases provided by Web Plattform Tests):

0. Test if URL is already encoded. Replace '+' encoded spaces with '%20' encoded spaces.

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

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$

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$"

}

回答8:

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 list = new ArrayList<>();

String rootUrl = url.split("\?")[0] + "?";

String paramsUrl = url.replace(rootUrl, "");

List 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

回答9:

In android I would use this code:

Uri myUI = Uri.parse ("http://example.com/query").buildUpon().appendQueryParameter("q","random word A3500 bank 24").build();

Where Uri is a android.net.Uri

回答10:

Use this: URLEncoder.encode(query, StandardCharsets.UTF_8.displayName()); or this:URLEncoder.encode(query, "UTF-8");

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);

java querystring_Java URL encoding of query string parameters相关推荐

  1. Query String Parameters、Form Data、Request Payload的区别

    Query String Parameters 当发起一次GET请求时,参数会以url string的形式进行传递.即?后的字符串则为其请求参数,并以&作为分隔符. 如下http请求报文头: ...

  2. http请求中的Query String Parameters、Form Data、Request Payload

    参考: (1).(http请求参数之Query String Parameters.Form Data.Request Payload) - https://www.jianshu.com/p/c81 ...

  3. query string parameters什么意思_public static void main(String[] args) 是什么意思?(转)...

    public static void main(String[] args),是java程序的入口地址,java虚拟机运行程序的时候首先找的就是main方法. 一.这里要对main函数讲解一下,参数S ...

  4. PHP的postman的bulk edit小功能:可以直接复制浏览器query string parameters的数据至postman的body的form-data 很方便 不用手写了

  5. Android之URL “page={page}category_id={***} string For dynamic query parameters use @Query.

    1.问题 我们用retrofit进行Get网络请求的时候,我代码是这样写的 @GET("/api/get_****/***?page={page}&category_id={cate ...

  6. A Filter of Java URL Encoding: GetQueryStringEn...

    2019独角兽企业重金招聘Python工程师标准>>> Spring的CharacterEncodingFilter 只能对post参数转码:要解决get中文乱码还得用这个: imp ...

  7. 用Python实现URL Encoding和Decoding

    前些日子在一个论坛上看到网友拿03版<天龙八部>和13版<天龙八部>作对比.在比较两个版本的片尾曲的时候,提到了03版的片尾曲<宽恕>.帖子中提到,这首歌由王菲演唱 ...

  8. 对Java的URL类支持的协议进行扩展的方法

    转载自   对Java的URL类支持的协议进行扩展的方法 JAVA默认提供了对file,ftp,gopher,http,https,jar,mailto,netdoc协议的支持.当我们要利用这些协议来 ...

  9. java http url 编码_Java中的HTTP URL地址编码

    java.net.URI类可以帮助;在URL的文档中找到 Note, the URI class does perform escaping of its component fields in ce ...

最新文章

  1. openlayer右键菜单_使用OpenLayers3 添加地图鼠标右键菜单
  2. UA MATH575B 数值分析下 计算统计物理例题2
  3. 互联网1分钟 | 0920
  4. c语言二维图形变换程序,【计算机图形学】3-2 二维几何变换根本代码
  5. ORA-01861: 文字与格式字符串不匹配
  6. python socket udp_python网络-Socket之udp编程(24)
  7. 多媒体计算机技术的主要特点,多媒体技术主要特点?
  8. mysql 数据库复制软件_mysql 快速复制数据库
  9. C# : 操作Word文件的API - (将C# source中的xml注释转换成word文档)
  10. 华为harmonyOS开发者日,华为首届HarmonyOS开发者创新大赛收官
  11. VS2008下的配置opencv
  12. 要管理组策略 您必须以域用户账户登录此计算机,让AD域用户账户只能登陆管理员指定的客户端计算机...
  13. 要关闭python解释器用什么快捷键_Python 解释器
  14. CDA-LEVEL 1 数据分析师一级经验总结
  15. 个人笔记本安装ubuntu系统
  16. 直升机救援机制的发展
  17. pla3d打印材料密度_FDM 3D打印机的常用耗材PLA的密度 创想三维
  18. 微信开放平台扫码登录
  19. 互联网金融系列-支付清算体系介绍-下篇
  20. python成都 培训

热门文章

  1. 7、android高级控件(2)(列表类视图)
  2. html播放rtsp视频,浏览器播放rtsp视频流解决方案
  3. java根据生日计算年龄工具类
  4. iphoneX 屏幕失灵误区
  5. 勿忘初心,保持饥渴的心态
  6. 在思科设备上使用华三光模块
  7. 安全区块链(区块链合约安全查询)
  8. js php通讯录,基于aotu.js实现微信自动添加通讯录中的联系人功能
  9. 江苏省C语言二级备考(2/20)
  10. 敏捷开发之Scrum