如何从URL获取(提取)/设置参数? [英] How to get(extract)/set parameters from URL?

查看:119
本文介绍了如何从URL获取(提取)/设置参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的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+

我需要按名称( sourceid, ion,...)获取/设置参数的值。我怎样才能做到这一点?
Delphi具有TIdURI类,它有助于解析URL,但不能解析参数,它将所有参数作为单个字符串(属性Params)返回。当然我可以创建自己的解析器,但是它是如此基本的功能,应该有一些标准方法(我希望)。我很惊讶TIdURI没有它。

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.

推荐答案

您需要先将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;

这篇关于如何从URL获取(提取)/设置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆