转义 HttpClient 请求的 URL 中的 & 符号
所以我有一些使用 Jakarta HttpClient 的 Java 代码,如下所示:
URI aURI = new URI( "http://host/index.php?title=" + title + "&action=edit" );
GetMethod aRequest = new GetMethod( aURI.getEscapedPathQuery());
问题是,如果 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"));
但是必须有更好的方法来做到这一点,对吗?请注意,标题可以包含任意数量的不可预测的 UTF-8 字符等,因此需要转义其他所有内容。
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());
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"));
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这里:
检查 java.net.URLEncoder< /a> 了解更多信息。
Here you go:
Check java.net.URLEncoder for more info.
如果您不想转义,为什么要调用 getEscapedPathQuery() ?只需确定谁的责任并保持一致即可。
Why are you calling getEscapedPathQuery() if you don't want the escaping? Just decide who's responsibility it is and be consistent.
使用 URLEncoder 类。
Use the URLEncoder class.