且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从URL获取(提取)/设置参数?

更新时间:2023-02-23 22:02:45

您需要先将URL解析为其组件,然后才能对其进行解码参数。

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;

要创建新的URL,只需逆向执行以下过程:

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;