我在 Delphi 中呼叫一個 API,它的回應是一個 pdf 檔案。我正在使用 MimeType application-pdf 獲取 IHttpResponse。如何從此回應創建 pdf 檔案?
代碼:
response := Form1.NetHTTPClient1.Post(apiurl,parametres, nil, headerparams);
responsestring := response.ContentAsString(tencoding.UTF8);
Form1.memo.Lines.Add(responsestring);
當我嘗試將回應轉換為ContentAsString以下錯誤時:

我什至嘗試在發布請求中傳遞一個 TStream 物件:
response := Form1.NetHTTPClient1.Post(apiurl,parametres, resStream, headerparams);
responsestring := response.ContentAsString(tencoding.UTF8);
Form1.memo.Lines.Add(responsestring);
但是在 Post 呼叫之后 resStream 的值是 '' 。回應代碼即將到來 200,這意味著我收到了回應。
在郵遞員中,當我嘗試這個時,我得到一個 pdf 檔案作為回應。
uj5u.com熱心網友回復:
您不能將二進制 PDF 檔案視為 UTF-8 字串,這就是ContentAsString()失敗并出現編碼錯誤的原因。
根據TNetHttpClient.Post()檔案:
如果您希望在 HTTP 客戶端從目標服務器下載回應資料時接收回應資料,而不是等待您的 HTTP 客戶端下載整個資料,請使用
AResponseContent引數指定一個流來接收下載的資料。或者,您可以等待您的 HTTP 客戶端下載整個回應資料,并從[ ] 回傳的回應物件ContentStream的屬性中以流的形式獲取回應資料。Post
因此,這些方法中的任何一種都應該可以正常作業:
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;
如果它們不適合您,您需要向Embarcadero提交錯誤報告。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/460938.html
