0

In Delphi XE7 it is advised to use TNetEncoding.URL.Encode

So far I have been using a custom routine:

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;

Using the method above I have been able to manually specify whether the encoded parameter S is a part of the Path or a part of the Query string.

The spaces should be encoded as + if found in the Path and as %20 is part of the Query parameters.

The function above emits properly

Url := 'http://something/?q=' + THttp.UrlEncode('koko jambo', true);
// Url := http://something/?q=koko%20jambo

but the following is returning different value

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

Please elaborate in what way TNetEncoding.URL.Encode should be properly used for encoding query parameters containing spaces as %20?

4

1 回答 1

1

阅读文档:

System.NetEncoding.TURLEncoding

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

无法将TNetEncoding.URL.Encode编码空间设为%20.

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

于 2014-10-19T23:50:15.927 回答