jpa*_*kal 5 java url escaping http apache-commons-httpclient
所以我有一些使用Jakarta HttpClient的Java代码:
URI aURI = new URI( "http://host/index.php?title=" + title + "&action=edit" );
GetMethod aRequest = new GetMethod( aURI.getEscapedPathQuery());
Run Code Online (Sandbox Code Playgroud)
问题是如果title包含任何&符号(&),它们被认为是参数分隔符,请求变得棘手......如果我用URL转义的等价物替换它们%26,那么getEscapedPathQuery()会将其双重转义%2526.
我目前正在通过基本修复损坏来解决这个问题:
URI aURI = new URI( "http://host/index.php?title=" + title.replace("&", "%26") + "&action=edit" );
GetMethod aRequest = new GetMethod( aURI.getEscapedPathQuery().replace("%2526", "%26"));
Run Code Online (Sandbox Code Playgroud)
但是必须有一个更好的方法来做到这一点,对吧?请注意,标题可以包含任意数量的不可预测的UTF-8字符等,因此必须转义其他所有字符.
Str*_*lok 14
干得好:
import java.net.URLEncoder;
...
...
URI aURI = new URI( "http://host/index.php?title=" + URLEncoder.encode(title,"UTF-8") + "&action=edit" );
GetMethod aRequest = new GetMethod( aURI.getPathQuery());
Run Code Online (Sandbox Code Playgroud)
查看java.net.URLEncoder以获取更多信息.