how do I encode a complete http url String correctly?

坚强是说给别人听的谎言 提交于 2019-12-20 02:32:19

问题


I get a url string from a user and would like to transform it to a legal http url:

"http://one.two/three?four five" should turn into "http://one.two/three?four%20five"

however, URLEncoder does not help, as it encodes the entire string (including the legal "://").

help?


回答1:


With external library:

import org.apache.commons.httpclient.util.URIUtil;
String myUrl_1= "http://one.two/three?four five";
System.out.println(URIUtil.encodeQuery(myUrl_1));

And the output:

http://one.two/three?four%20five

Or

String webResourceURL = "http://stackoverflow.com/search?q=<script>alert(1)</script> s";
System.out.println(URIUtil.encodeQuery(webResourceURL));

And the output:

http://stackoverflow.com/search?q=%3Cscript%3Ealert(1)%3C/script%3E%20s

And the Maven dependency

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>



回答2:


Use the URL class. For example:

URL url = new URL(urlString);
String encodedQueryString = URLEncoder.encode(url.getQuery());
String encodedUrl = urlString.replace(url.getQuery(), encodedQueryString);

The third line might be different - for example constructing a new URL from all its parts.



来源:https://stackoverflow.com/questions/3292579/how-do-i-encode-a-complete-http-url-string-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!