You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TMS Web Core中通过Delphi代码获取URL查询字符串参数?

用纯Delphi代码提取URL中的查询字符串参数

要从指定URL中提取目标查询参数,我们可以通过原生字符串处理+Delphi自带编码工具实现,无需依赖外部库或JavaScript。以下是具体实现方案:

实现思路

  1. 定位URL中的?分隔符,分离出查询字符串片段;
  2. 将查询字符串按&分割为单个参数项;
  3. 对每个参数项按=拆分,提取键名与对应值;
  4. 匹配目标参数名,返回对应值(自动处理URL编码的参数值)。

通用提取函数

uses
  System.SysUtils, System.NetEncoding;

function GetQueryParam(const AURL, AParamName: string; const AIgnoreCase: Boolean = True): string;
var
  LQueryStart: Integer;
  LQueryString: string;
  LParams: TArray<string>;
  LParam: string;
  LEqualPos: Integer;
  LKey, LValue: string;
begin
  Result := '';
  // 定位查询字符串起始位置
  LQueryStart := Pos('?', AURL);
  if LQueryStart = 0 then Exit;

  LQueryString := Copy(AURL, LQueryStart + 1, MaxInt);
  // 分割所有参数项
  LParams := LQueryString.Split(['&']);

  for LParam in LParams do
  begin
    LEqualPos := Pos('=', LParam);
    if LEqualPos = 0 then Continue;

    LKey := Copy(LParam, 1, LEqualPos - 1);
    LValue := Copy(LParam, LEqualPos + 1, MaxInt);

    // 匹配参数名,支持大小写忽略
    if (AIgnoreCase and SameText(LKey, AParamName)) or SameStr(LKey, AParamName) then
    begin
      // 解码URL编码的参数值(比如%20转空格)
      Result := TNetEncoding.URL.Decode(LValue);
      Break;
    end;
  end;
end;

调用示例

针对你提供的URL https://www.example.com/index.html?first_name=shaun&last_name=roselt,提取参数的代码如下:

var
  LURL: string;
  LFirstName, LLastName: string;
begin
  LURL := 'https://www.example.com/index.html?first_name=shaun&last_name=roselt';
  LFirstName := GetQueryParam(LURL, 'first_name');
  LLastName := GetQueryParam(LURL, 'last_name');

  // 输出结果:first_name=shaun,last_name=roselt
  ShowMessage(Format('first_name=%s'#13'last_name=%s', [LFirstName, LLastName]));
end;

补充说明

  • 若目标参数不存在,函数返回空字符串;
  • 默认忽略参数名大小写,如需严格匹配,调用时将AIgnoreCase设为False;
  • TNetEncoding.URL.Decode适用于Delphi XE7及以上版本,低版本若要纯原生实现,可自行编写URL解码逻辑替代。

内容的提问来源于stack exchange,提问作者Shaun Roselt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:13:25