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

萝らか妹 提交于 2020-04-17 07:18:40

问题


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.


回答1:


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;



回答2:


Use TURI from System.Net.URLClient unit

This is a record, first you need to load address string : TUri.create('http://google.com').

Then you can use MyUri.ParameterByName['param'].

Also it can URLEncode URLDecode, AddParameter, DeleteParameter property Parameter[const I: Integer] (TNameValuePair) etc



来源:https://stackoverflow.com/questions/26315801/how-to-getextract-set-parameters-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!