标准URL编码功能?

Bor*_*ens 43 delphi

是否有这个.net方法的Delphi等价物:

Url.UrlEncode()

注意
我已经好几年没用Delphi了.在我阅读答案时,我注意到当前标记的答案有几个备注和备选方案.我没有机会测试它们,所以我的答案基于最受欢迎的.
为了您自己的利益,请检查以后的答案,并在决定提出最佳答案后,以便每个人都可以从您的经验中受益.

Moh*_*man 95

看看indy IdURI单元,它在TIdURI类中有两个静态方法用于Encode/Decode URL.

uses
  IdURI;

..
begin
  S := TIdURI.URLEncode(str);
//
  S := TIdURI.URLDecode(str);
end;
Run Code Online (Sandbox Code Playgroud)

  • 但请注意Marc Durdin博客文章"Indy,TIdURI.PathEncode,URLEncode和ParamsEncode等"中的警告,网址为http://marc.durdin.net/2012/07/indy-tiduripathencode-urlencode-and.html (15认同)
  • 鲍里斯,来吧,接受这个答案,我只是给了它一点完全有帮助:) (6认同)
  • Indy工作不正常,所以你需要查看这篇文章:http://marc.durdin.net/2012/07/indy-tiduripathencode-urlencode-and.html (6认同)
  • @Peter Heh,我没有检查这个问题因为我不再使用Delphi了.但无论如何你要去;) (3认同)
  • 从Delphi xe7开始,您可以使用TNetEncoding.Url.Encode(),它是一种更智能的方式,独立于Indi Components (3认同)

Ali*_*ter 19

另一种简单的方法是在HTTPApp单元中使用HTTPEncode函数 - 非常粗略

Uses 
  HTTPApp;

function URLEncode(const s : string) : string;
begin
  result := HTTPEncode(s);
end
Run Code Online (Sandbox Code Playgroud)


ska*_*adt 13

另一种选择是使用SyapCode单元中具有简单URL编码方法(以及许多其他方法)的Synapse库.

uses
  SynaCode;
..
begin
  s := EncodeUrl( str );
//
  s := DecodeUrl( str );
end;
Run Code Online (Sandbox Code Playgroud)


WeG*_*ars 13

更新2018:下面显示的代码似乎已过时.看雷米的评论.

class function TIdURI.ParamsEncode(const ASrc: string): string;
var
  i: Integer;
const
  UnsafeChars = '*#%<> []';  {do not localize}
begin
  Result := '';    {Do not Localize}
  for i := 1 to Length(ASrc) do
  begin
    if CharIsInSet(ASrc, i, UnsafeChars) or (not CharIsInSet(ASrc, i, CharRange(#33,#128))) then begin {do not localize}
      Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2);  {do not localize}
    end else begin
      Result := Result + ASrc[i];
    end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

来自印地.


无论如何,Indy工作不正常,所以你需要看看这篇文章:http:
//marc.durdin.net/2012/07/indy-tiduri-pathencode-urlencode-and-paramsencode-and-more/

  • 祭坛和Marc Durdin是对的.TIdURI坏了.单元REST.Utils提供了一个正常工作的函数URIEncode. (8认同)

Rad*_*dík 13

我自己创建了这个函数来编码除了非常安全的字符之外的所 特别是我有+问题.请注意,您无法使用此函数对整个URL进行编码,但您需要包含您想要没有特殊含义的部分,通常是变量的值.

function MyEncodeUrl(source:string):string;
 var i:integer;
 begin
   result := '';
   for i := 1 to length(source) do
       if not (source[i] in ['A'..'Z','a'..'z','0','1'..'9','-','_','~','.']) then result := result + '%'+inttohex(ord(source[i]),2) else result := result + source[i];
 end;
Run Code Online (Sandbox Code Playgroud)


Enn*_*nny 11

从Delphi xe7开始,您可以使用TNetEncoding.Url.Encode()


Sti*_*ers 6

在非dotnet环境中,Wininet单元提供对Windows的WinHTTP编码功能的访问: InternetCanonicalizeUrl


Jam*_*coe 5

在最新版本的Delphi(使用XE5测试)中,使用REST.Utils单元中的URIEncode函数.