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

Delphi 12中RestRequest.Resource触发访问冲突问题求助

问题分析与解决

核心原因

你在finally块里手动释放了RESTClient1、RESTRequest1组件,但这些组件是设计阶段添加到窗体上的(非动态创建),生命周期由窗体自动管理。手动释放后,组件内存被回收,第二次点击按钮时再访问RESTRequest1.Resource就会触发访问违规错误,程序退出时也会因组件已被提前释放而报错。

修复方案

  1. 彻底移除finally块中对RESTClient1、RESTRequest1的释放代码,这类组件不需要手动释放。
  2. 调整JsonValue的内存管理:RESTResponse1.JSONValue返回的对象由RESTResponse1负责管理,无需手动调用Free,否则可能引发重复释放问题。

修正后的代码

procedure TAffiche.Button1Click(Sender: TObject);
var
  PointLong     : string;
  PointLat      : string;
  JsonValue     : TJSONValue;
  Elevation     : string;
  Resource      : string;
begin
  if not DetectionConnexion then
  begin
    raise Exception.Create('Internet connection not available.');
  end
  else
  begin
    try
      MemoData.Clear;
      PointLong := LongRef;
      PointLat  := LatRef;
      // 注意:直接使用&即可,无需用HTML转义的&
      Resource  := 'elevation.json?lon=' + PointLong + '&lat=' + PointLat + '&indent=true';
      RESTRequest1.Resource := Resource;
      RESTRequest1.Execute;
      JsonValue := RESTResponse1.JSONValue;
      // 增加空判断,避免API返回空数据时出错
      if Assigned(JsonValue) then
      begin
        Elevation := JsonValue.GetValue<string>('elevations[0].z');
        MemoData.Lines.Add('获取到的高程:' + Elevation);
      end;
    finally
      // 移除所有不必要的手动释放代码
    end;
  end;
end;

额外提示

  • 代码中的&amp;是HTML转义字符,直接替换为&才能被API正确解析参数。
  • 访问JSON节点前增加Assigned(JsonValue)判断,可避免API返回异常数据时触发崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:02:39