gpt4 book ai didi

java - 在 URL 中为 http post 编码参数和值或只编码值?

转载 作者:行者123 更新时间:2023-11-29 04:53:22 25 4
gpt4 key购买 nike

我有一个提交 http post 请求的 Java 类。我有查询参数,我的问题是我需要对名称=值对还是只对值进行编码。

String query = "foo=abc&bar=efg";

String encodedQuery = URLEncoder.encode("foo=abc&bar=efg","utf-8");

String query = "foo=" + URLEncoder.encode("abc","utf-8") + "&" + "bar=" + URLEncoder.encode("efg","utf-8");

最佳答案

调用 URLEncoder.encode 以确保您的 URI 中没有不安全的字符。不安全的字符几乎是所有不是字母、数字和一些特殊字符的字符。

来自 URLEncoder 的 java-doc

The alphanumeric characters "a" through "z", "A" through "Z" and "0" through >"9" remain the same. The special characters ".", "-", "*", and "_" remain the same. The space character " " is converted into a plus sign "+". All other characters are unsafe and are first converted into one or more bytes >using some encoding scheme. Then each byte is represented by the 3-character >string "%xy", where xy is the two-digit hexadecimal representation of the byte. >The recommended encoding scheme to use is UTF-8. However, for compatibility >reasons, if an encoding is not specified, then the default encoding of the >platform is used.

例子:

String query = "foo=abc&bar=def";

所以。如果您对整个查询进行编码,它将导致

foo%3Dabc%26bar%3Defg

在这种情况下,您还对分隔查询部分所需的 = 和 & 进行了编码。

您必须对查询的名称和值进行编码,以确保它们不包含不安全的字符。例如&、= 和任何不可打印/特殊字符。如果你知道你的名字只包含安全字符,你就不必对名字进行编码。

String param1 = URLEncoder.encode("abc", "utf-8");
String param2 = URLEncoder.encode("a&b", "utf-8");
String query = "foo=" + param1 + "&bar=" + param2;

结果

foo=abc&bar=a%26b

这应该是您需要的查询。请注意 param2 中的 & 将被编码,因为它对于有效的 url 是“不安全的”!

关于java - 在 URL 中为 http post 编码参数和值或只编码值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34616399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com