HttpURLConnection 和 URL 中的编码字符

发布于 2025-01-07 21:09:51 字数 775 浏览 2 评论 0 原文

我有这样的代码:

URL url = new URL("http://foo.com/?param=paj%E9");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
...

但是,似乎 openConnection 正在抑制 url 的“%E9”部分,并且服务器最终收到请求 http://foo.com?param=paj

我是否忘记应用任何不同的设置才能使其正常工作?

谢谢!

编辑: url“http://foo.com/?param=paj%E9”已经编码(来自 http:// /foo.com/?param=pajé),这应该是服务器应该接收的请求。如果我尝试直接访问 http://foo.com/?param=paj%E9从浏览器来看,它按预期工作。如果我对“paj%E9”进行 URLEncode,我将对参数进行双重编码,并且服务器在解码该值时会看到“paj%E9”而不是“pajé”。 我实际上正在尝试构建一个代理,因此我收到了已经编码的网址。问题是,每当我使用 HttpURLConnection 传递要请求的此类编码参数时,它都会忽略编码部分(如 %E9)。

I have a code like this:

URL url = new URL("http://foo.com/?param=paj%E9");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
...

However, it seems like the openConnection is supressing the "%E9" part of the url, and the server ends up receiving a request http://foo.com?param=paj

Am I forgetting to apply any different setting for this to work properly?

Thanks!

EDIT: The url "http://foo.com/?param=paj%E9" is already encoded (from http://foo.com/?param=pajé), and this should be the request the server should receive. If I try to access http://foo.com/?param=paj%E9 straight from the browser, it works as expected. If I URLEncode "paj%E9", I'll be double-encoding the parameter, and the server would see "paj%E9" instead "pajé" upon decoding the value.
I'm actually trying to build a proxy, and therefore I receive the urls already encoded. The problem is that whenever I pass such an encoded parameter to be requested using HttpURLConnection, it simply ignores the encoded part (like %E9).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只有一腔孤勇 2025-01-14 21:09:51

您需要使用 java.net.URI 类来编码您的 URL,而不是您自己处理它。检查这个:
Java 中的 HTTP URL 地址编码

You need to use java.net.URI class to encode your URL instead of handle it on your own. Chek this:
HTTP URL Address Encoding in Java

云裳 2025-01-14 21:09:51

您可以使用以下代码
URLEncoder.encode("中文", "utf-8")

You can use the following code
URLEncoder.encode("中文", "utf-8")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文