Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Lazarus/Delphi - How to encode an URL with a simple function

2 Posts
1 Users
0 Reactions
3,275 Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

For one of my apps I had to encode a search string in a URL (to get results from Google).
For this the text had to be Encoded.
This procedure will do just that: URL Encode ...

function HTTPEncode(const AStr: string): string; 
const 
  NoConversion = ['A'..'Z', 'a'..'z', '*', '@', '.', '_', '-']; 
var 
  Sp, Rp: PChar; 
begin 
  SetLength(Result, Length(AStr) * 3); 
  Sp := PChar(AStr); 
  Rp := PChar(Result); 
  while Sp^ <> #0 do 
  begin 
    if Sp^ in NoConversion then 
      Rp^ := Sp^ 
    else if Sp^ = ' ' then 
      Rp^ := '+' 
    else 
    begin 
      FormatBuf(Rp^, 3, '%%%.2x', 6, [Ord(Sp^)]); 
      Inc(Rp, 2); 
    end; 
    Inc(Rp); 
    Inc(Sp); 
  end; 
  SetLength(Result, Rp - PChar(Result)); 
end; 

   
ReplyQuote
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

A good alternative:

function URLEncode(s: string): string;
var
  i: integer;
  source: PAnsiChar;
begin
  result := '';
  source := pansichar(s);
  for i := 1 to length(source) do
    if not (source in ['A'..'Z', 'a'..'z', '0'..'9', '-', '_', '~', '.', ':', '/']) then
      result := result + '%' + inttohex(ord(source), 2)
    else
      result := result + source;
end;            

   
ReplyQuote
Share: