转换HttpClient请求的URL中的&符号 [英] Escaping ampersands in URLs for HttpClient requests
问题描述
所以我有一些使用Jakarta HttpClient的Java代码,如下所示:
So I've got some Java code that uses Jakarta HttpClient like this:
URI aURI = new URI( "http://host/index.php?title=" + title + "&action=edit" );
GetMethod aRequest = new GetMethod( aURI.getEscapedPathQuery());
问题是如果标题
包含任何&符号(&),它们被认为是参数分隔符,并且请求变得灵活...如果我用URL转义的等价物%26
替换它们,那么这将获得通过getEscapedPathQuery()双重转义为%2526
。
The problem is that if title
includes any ampersands (&), they're considered parameter delimiters and the request goes screwy... and if I replace them with the URL-escaped equivalent %26
, then this gets double-escaped by getEscapedPathQuery() into %2526
.
我正在通过基本修复损坏之后:
I'm currently working around this by basically repairing the damage afterward:
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字符等,所以逃避一切都是一个要求。
But there has to be a nicer way to do this, right? Note that the title can contain any number of unpredictable UTF-8 chars etc, so escaping everything else is a requirement.
推荐答案
你去:
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 获取更多信息。
这篇关于转换HttpClient请求的URL中的&符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!