Search code examples
delphiurldelphi-xe7

How to get(extract)/set parameters from URL?


I have URL like this (for example):

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=delphi+url+parameters+

I need to get/set value of parameter by name ("sourceid", "ion", ...). How can i do this? Delphi has TIdURI class, it helps to parse URL but not parameters, it returns all parameters as single string (property Params). Of course i can create my own parser but it is so basic functionality, there should be some standard way (i hope). I surprised that TIdURI doesn't have it.


Solution

  • You need to parse the URL into its components first, then you can decode the parameters.

    Url := 'https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=delphi+url+parameters+';
    
    Params := TStringList.Create;
    try
      Params.Delimiter := '&';
      Params.StrictDelimiter := true;
    
      Uri := TIdURI.Create(Url);
      try
        Params.DelimitedText := Uri.Params;
      finally
        Uri.Free;
      end;
    
      for i := 0 to Params.Count -1 do
      begin
        Params.Strings[i] := StringReplace(Params.Strings[i], '+', ' ', [rfReplaceAll]);
        Params.Strings[i] := TIdURI.URLDecode(Params.Strings[i], enUtf8);
      end;
    
      // use Params as needed...
    
    finally
      Params.Free;
    end;
    

    To create a new URL, just reverse the process:

    Params := TStringList.Create;
    try
    
      // fill Params as needed...
    
      for i := 0 to Params.Count -1 do
      begin
        Params.Strings[i] := TIdURI.ParamsEncode(Params.Names[i], enUtf8) + '=' + TIdURI.ParamsEncode(Params.ValueFromIndex[i], enUtf8);
        Params.Strings[i] := StringReplace(Params.Strings[i], ' ', '+', [rfReplaceAll]);
      end;
    
      Params.Delimiter := '&';
      Params.StrictDelimiter := true;
    
      Uri := TIdURI.Create('');
      try
        // fill other Uri properties as needed...
        Uri.Params := Params.DelimitedText;
        URL := Uri.URI;
      finally
        Uri.Free;
      end;
    finally
      Params.Free;
    end;