Delphi 如何使用tnetencode.URL.Encode对查询字符串参数中的空格进行编码?

Delphi 如何使用tnetencode.URL.Encode对查询字符串参数中的空格进行编码?,delphi,encoding,delphi-xe7,Delphi,Encoding,Delphi Xe7,在Delphi XE7中,建议使用tnetencode.URL.Encode 到目前为止,我一直在使用自定义例程: class function THttp.UrlEncode(const S: string; const InQueryString: Boolean): string; var I: Integer; begin Result := EmptyStr; for i := 1 to Length(S) do case S[i] of // The No

在Delphi XE7中,建议使用tnetencode.URL.Encode

到目前为止,我一直在使用自定义例程:

class function THttp.UrlEncode(const S: string; const InQueryString: Boolean): string;
var
  I: Integer;
begin
  Result := EmptyStr;
  for i := 1 to Length(S) do
    case S[i] of
    // The NoConversion set contains characters as specificed in RFC 1738 and
    // should not be modified unless the standard changes.
    'A'..'Z', 'a'..'z', '*', '@', '.', '_', '-', '0'..'9', 
    '$', '!', '''', '(', ')':
       Result := Result + S[i];
    '—': Result := Result + '%E2%80%94';
    ' ' :
      if InQueryString then
        Result := Result + '+'
      else
        Result := Result + '%20';
   else
     Result := Result + '%' + System.SysUtils.IntToHex(Ord(S[i]), 2);
   end;
end;
使用上述方法,我能够手动指定编码参数S是路径的一部分还是查询字符串的一部分

如果在路径中找到空格,则应将其编码为+并且%20是查询参数的一部分

上述功能正常发射

Url := 'http://something/?q=' + THttp.UrlEncode('koko jambo', true);
// Url := http://something/?q=koko%20jambo
但是下面返回的是不同的值

Url := 'http://something/?q=' + TNetEncoding.URL.Encode('koko jambo;);
// Url := http://something/?q=koko+jambo

请详细说明如何正确使用tnetencode.URL.Encode将包含空格的查询参数编码为%20?

阅读文档:

TURLEncoding仅编码空格(加号:+)和以下保留URL编码字符:;:&=+,/?%#[…]

无法使
tnetencode.URL.Encode
将空格编码为
%20


通常,我会建议Indy的
TIdURI
类,因为它有单独的
PathEncode()
ParamsEncode()
方法,但它们都将空格编码为
%20
,这不满足您的“在路径中找到时编码为+”要求。

最后一段读起来有点奇怪。“通常,我建议……,但它们也将空格编码为
%20
”。将空格编码为
%20
不正是我们想要的吗?或者您是错误地编写了
%20
,意思是
+
?@DavidHeffernan:阅读OP的要求:“如果在路径中找到空格,则应将空格编码为+,因为%20是查询参数的一部分。”答案的最后一部分说,“但它们都将空格编码为%20”。这不是我们想要的吗。还是PathEncode()和ParamsEncode()将url和查询中的空格都编码为%20的问题?@DavidHeffernan:后者。只是多年后的一个注释。您在这里讨论的是URL编码和URI编码之间的区别。在JS中,URI编码是通过EncodeURIComponent完成的,EncodeURIComponent具有扩展的编码字符范围。此外,源字符编码必须是(UTF8、16、asci、misc iso)的高度。