如何正确编码完整的http url字符串? [英] how do I encode a complete http url String correctly?
本文介绍了如何正确编码完整的http url字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从用户那里获得了一个url字符串,并希望将其转换为合法的http url:
I get a url string from a user and would like to transform it to a legal http url:
" http://one.two/three?four 五"应该变成" http://one.two/three?four%20five "
"http://one.two/three?four five" should turn into "http://one.two/three?four%20five"
但是,URLEncoder却无济于事,因为它会编码整个字符串(包括合法的://").
however, URLEncoder does not help, as it encodes the entire string (including the legal "://").
帮助?
推荐答案
使用外部库:
import org.apache.commons.httpclient.util.URIUtil;
String myUrl_1= "http://one.two/three?four five";
System.out.println(URIUtil.encodeQuery(myUrl_1));
输出:
http://one.two/three?four%20five
或
String webResourceURL = "http://stackoverflow.com/search?q=<script>alert(1)</script> s";
System.out.println(URIUtil.encodeQuery(webResourceURL));
输出:
http://stackoverflow.com/search?q=%3Cscript%3Ealert(1)%3C/script%3E%20s
与Maven的依赖关系
And the Maven dependency
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
这篇关于如何正确编码完整的http url字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文