Delphi REST 服务器、Android 客户端使用压缩

bos*_*vos 3 delphi rest http-compression datasnap delphi-xe3

我们正在构建一个 Delphi REST 服务器,该服务器向本机 Android 应用程序提供相当大的数据块(每个请求 1.5MB,数量很多)。一切正常,除了这种情况下的数据大小会出现问题,导致我们的环境中传输时间较长(移动数据速率有限)。我尝试ZLibCompression在 上添加过滤器DSHTTPWebDispatcher,但响应仅以未压缩的文本/html 形式再次返回。

有没有办法强制服务器使用在调度之前作为事件添加的过滤器?

服务器采用Delphi XE3构建。

bos*_*vos 5

我已经设法找出在 DataSnap 项目中添加压缩和相关标头更改的位置。

这里的关键是 TWebModule 类。如果使用向导创建一个新项目,则会构建 TWebModule 类的默认实现,其中包含 BeforeDispatch、AfterDispatch 等事件属性。此处的命名是指将传入请求分派到将要处理的位置的操作。因此,BeforeDispatch 在请求到达时发生,服务器上发生一些处理,而 AfterDispatch 在响应发送回调用者之前触发。

因此,如果您想在事后修改构造的响应,则 AfterDispatch 是正确的事件。这可以包括对内容和标题的更改。

在 AfterDispatch 事件上:

procedure TWebModule1.WebModuleAfterDispatch(
  Sender: TObject;
  Request: TWebRequest; 
  Response: TWebResponse;
  var Handled: Boolean);
var

srcbuf, destbuf : TBytes;
str : string;

begin
  str := Response.Content;

  //prepare byte array
  srcbuf := BytesOf(str);

  //compress to buff (System.ZLib)
  ZCompress(srcbuf, destbuf, zcMax);

  //prepare responsestream and set content encoding and type
  Response.Content := '';
  Response.ContentStream := TMemoryStream.Create;
  Response.ContentEncoding := 'deflate';
  Response.ContentType := 'application/json';

  //current browser implementations incorrectly handles the first 2 bytes 
  //of a ZLib compressed stream, remove them
  Response.ContentStream.Write(@(destbuf[2]),length(destbuf)-2);
  Response.ContentLength := (length(destbuf))-2;
end;
Run Code Online (Sandbox Code Playgroud)

不是很花哨,可以根据发回的内容启用/禁用压缩,但对于我们的实现,我们保持简单。

这对于 Fiddler 和可以处理 deflate 的浏览器 100% 有效。