如何正确编码完整的http url字符串?

Ami*_*rad 3 java urlencode

我从用户那里得到一个url字符串,并希望将其转换为合法的http url:

" http://one.two/three?四五 "应该变成" http://one.two/three?four%20five "

但是,URLEncoder没有帮助,因为它编码整个字符串(包括合法的"://").

救命?

Boz*_*zho 6

使用该URL课程.例如:

URL url = new URL(urlString);
String encodedQueryString = URLEncoder.encode(url.getQuery());
String encodedUrl = urlString.replace(url.getQuery(), encodedQueryString);
Run Code Online (Sandbox Code Playgroud)

第三行可能不同 - 例如URL从其所有部分构建新的.


Xel*_*ian 5

使用外部库:

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

和输出:

http://one.two/three?four%20five
Run Code Online (Sandbox Code Playgroud)

或者

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

和输出:

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

以及 Maven 依赖

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)