使用 URL 中含有非法字符的 HttpGet
我正在尝试使用 DefaultHttpClient
和 HttpGet
向 Web 服务发出请求。不幸的是,Web 服务 URL 包含非法字符,例如 {(例如:domain.com/service/{username})。很明显,Web 服务命名写得不好,但我无法更改它。
当我执行 HttpGet(url)
时,我发现 url 中存在非法字符(即 { 和 })。如果我在此之前对 URL 进行编码,则不会出现错误,但请求会转到另一个没有任何错误的 URL。
该网址虽然包含非法字符,但可以在浏览器中使用,但 HttpGet
实现不允许我使用它。我应该做什么或使用什么来避免这个问题?
I am trying to use DefaultHttpClient
and HttpGet
to make a request to a web service. Unfortunately the web service URL contains illegal characters such as { (ex: domain.com/service/{username}). It's obvious that the web service naming isn't well written but I can't change it.
When I do HttpGet(url)
, I get that I have an illegal character in the url (that is { and }). If I encode the URL before that, there is no error but the request goes to a different URL where there is nothing.
The url, although has illegal characters, works from the browser but the HttpGet
implementation doesn't let me use it. What should I do or use instead to avoid this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
http://java.sun.com/javase/6 /docs/api/java/net/URLEncoder.html
具体来说:
http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
Specifically:
我们不应该对 URL 的地址部分使用 URLEncoder.encode,因为它会错误地更改您的 http://domain.com/ {username} 到 http%3A%2F%2Fdomain.com%2{username} ,您应该知道它将用“+”替换所有空格,对我来说最好用“%20”替换它们。
此处,此函数仅对 URL 的最后部分进行编码,即 {username} 或文件名或任何可能包含非法字符的内容。
we shouldn't use URLEncoder.encode for address part of URL because it wrongly changes your http://domain.com/{username} to http%3A%2F%2Fdomain.com%2{username} and you should know it will replace all spaces with '+' that it was better to me to replace them with "%20".
Here this function encodes only last part of your URL which is {username} or file name or anything that may have illegal characters.
这个问题很老了,但它对我有帮助,我只是想为可能过来的人补充一点,我通过迈克的回复的变体在我的应用程序上解决了这个问题。
我发现只对相关部分进行编码是有效的,而尝试对整个 url 进行编码会给我带来错误。
This question is old but it helped me and I just wanted to add for anyone who might come by that I fixed this issue on my app with a variation of Mike's reply.
I found that encoding just the relevant parts worked, where attempting to encode the entire url caused an error for me.