从 MimeType 的 TNetHttpClient 获取响应 application/pdf

Fetch response from TNetHttpClient of MimeType application/pdf

我在 Delphi 中调用一个 API,它的响应是一个 pdf 文件。我收到 IHttpResponse,带有 MimeType application-pdf。如何根据此回复创建 pdf 文件?

代码:

response := Form1.NetHTTPClient1.Post(apiurl,parametres, nil, headerparams);
responsestring := response.ContentAsString(tencoding.UTF8);
Form1.memo.Lines.Add(responsestring);

当我尝试将响应转换为 ContentAsString 时出现以下错误:

我什至试图在 post 请求中传递一个 TStream 对象:

response := Form1.NetHTTPClient1.Post(apiurl,parametres, resStream, headerparams);
responsestring := response.ContentAsString(tencoding.UTF8);
Form1.memo.Lines.Add(responsestring);

但是在 Post 调用之后 resStream 的值是 ''。响应代码即将变为 200,这意味着我正在收到响应。

在 Postman 中,当我尝试此操作时,我得到一个 pdf 文件作为响应。

您不能将二进制 PDF 文件视为 UTF-8 字符串,这就是 ContentAsString() 因编码错误而失败的原因。

根据 TNetHttpClient.Post() 文档:

If you want to receive the response data as your HTTP client downloads it from the target server, instead of waiting for your HTTP client to download the whole data, use the AResponseContent parameter to specify a stream to receive the downloaded data. Alternatively, you can wait for your HTTP client to download the whole response data, and obtain the response data as a stream from the ContentStream property of the response object that [Post] returns.

因此,这些方法中的任何一种都应该可以正常工作:

response := Form1.NetHTTPClient1.Post(apiurl, parametres, nil, headerparams);
fs := TFileStream.Create('path\output.pdf', fmCreate);
try
  fs.CopyFrom(response.ContentStream, 0);
finally
  fs.Free;
end;
fs := TFileStream.Create('path\output.pdf', fmCreate);
try
  Form1.NetHTTPClient1.Post(apiurl, parametres, fs, headerparams);
finally
  fs.Free;
end;

如果它们不适合您,您将需要 file a bug report 与 Embarcadero。