Standard URL encode function?

Solution 1:

Look at indy IdURI unit, it has two static methods in the TIdURI class for Encode/Decode the URL.

uses
  IdURI;

..
begin
  S := TIdURI.URLEncode(str);
//
  S := TIdURI.URLDecode(str);
end;

Solution 2:

Another simple way of doing this is to use the HTTPEncode function in the HTTPApp unit - very roughly

Uses 
  HTTPApp;

function URLEncode(const s : string) : string;
begin
  result := HTTPEncode(s);
end

HTTPEncode is deprecated in Delphi 10.3 - 'Use TNetEncoding.URL.Decode'

Uses
  NetEncoding;

function URLEncode(const s : string) : string;
begin
  result := TNetEncoding.URL.Encode(s);
end

Solution 3:

I made myself this function to encode everything except really safe characters. Especially I had problems with +. Be aware that you can not encode the whole URL with this function but you need to encdoe the parts that you want to have no special meaning, typically the values of the variables.

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;

Solution 4:

Another option, is to use the Synapse library which has a simple URL encoding method (as well as many others) in the SynaCode unit.

uses
  SynaCode;
..
begin
  s := EncodeUrl( str );
//
  s := DecodeUrl( str );
end;