如何配置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
相关产品推荐
相关产品推荐

