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

如何配置RAD Server发送压缩响应?已设Accept-Encoding仍未生效

RAD Server 启用gzip压缩响应的实现方式

RAD Server默认不会自动识别Accept-Encoding请求头并返回压缩后的响应,你需要在服务器端手动实现压缩逻辑,具体步骤如下:

  • 检查客户端压缩支持:在请求处理流程中,读取请求头里的Accept-Encoding字段,判断是否包含gzip值。
  • 压缩响应内容:如果客户端支持gzip,使用Delphi自带的TZCompressionStream(需引用Zlib单元)对响应内容进行压缩。
  • 设置响应头:压缩完成后,给响应添加Content-Encoding: gzip头,同时调整响应流为压缩后的数据流,确保客户端能正确解压。

示例代码(Resource方法中实现)

uses Zlib;

procedure TMyDataResource.Get;
var
  RawContent: string;
  CompressedMS: TMemoryStream;
  GZipStream: TZCompressionStream;
begin
  // 生成原始响应内容(比如从数据库读取的大体积数据)
  RawContent := '这里是你的大响应内容,比如JSON格式的数据集';

  // 判断客户端是否支持gzip压缩
  if Pos('gzip', Request.Headers['Accept-Encoding']) > 0 then
  begin
    CompressedMS := TMemoryStream.Create;
    try
      // 创建gzip压缩流,zcFastest代表最快压缩速度,可按需换成zcMaxCompression
      GZipStream := TZCompressionStream.Create(CompressedMS, zcFastest);
      try
        // 写入原始内容到压缩流
        GZipStream.WriteBuffer(RawContent[1], Length(RawContent) * SizeOf(Char));
      finally
        GZipStream.Free;
      end;

      // 设置响应头和响应流
      Response.Headers.Add('Content-Encoding', 'gzip');
      Response.ContentType := 'application/json'; // 根据实际内容类型调整
      Response.ContentStream := CompressedMS;
      Response.ContentStream.Position := 0;
    except
      CompressedMS.Free;
      raise;
    end;
  end
  else
  begin
    // 不支持压缩时返回明文
    Response.Content := RawContent;
    Response.ContentType := 'application/json';
  end;
end;

全局优化方案

如果需要所有RAD Server的响应都支持gzip压缩,可以自定义请求拦截器(Interceptor),在拦截器的OnBeforeDispatch或OnAfterDispatch事件中统一处理压缩逻辑,避免每个Resource重复编写代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:50:08