Home > Net >  Fetch response from TNetHttpClient of MimeType application/pdf
Fetch response from TNetHttpClient of MimeType application/pdf

Time:04-07

I am calling an API in Delphi the response of which is a pdf file. I am getting IHttpResponse, with MimeType application-pdf. How can I create a pdf file from this response?

Code:

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

When I try to convert the response to ContentAsString the below error is coming:

enter image description here

I even tried to pass a TStream Object in the post request:

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

But the value of resStream is '' after Post call. The response code is coming 200 which means I am getting a response.

In Postman when I try this, I get a pdf file in response.

CodePudding user response:

You can't treat a binary PDF file as a UTF-8 string, which is why ContentAsString() is failing with an encoding error.

Per the TNetHttpClient.Post() documentation:

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.

So, either of these approaches should work fine:

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;

If they do not work for you, you will need to file a bug report with Embarcadero.

  • Related