因此,我有一些使用Jakarta HttpClient的Java代码,如下所示:
URI aURI = new URI( "http://host/index.php?title=" + title + "&action=edit" );
GetMethod aRequest = new GetMethod( aURI.getEscapedPathQuery());
问题是,如果
title
包含任何“与”号(&),它们将被视为参数定界符,并且请求变得繁琐...如果我将其替换为网址转义的等效%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"));
但是必须有更好的方法来做到这一点,对吗?请注意,标题可以包含任意数量的不可预测的UTF-8字符等,因此必须转义其他所有内容。
最佳答案
干得好:
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());
检查java.net.URLEncoder了解更多信息。