File Downloads using HttpClient
This post is just a little reminder to me and some of you might compassionately smile. But I have recently spent hours racking my brains why I only get “empty” files when I download a “simple” PDF using HttpClient in a Business Central AL extension (although file-size and general sizing of the pdf files were ok). I didn’t consider saving the response stream directly into an InStream instead of using a Text variable which i then stored in a blob field.
Why? Because I forgot about my own post about method overloading. ResponseMessage.Content.ReadAs(…) has an overload accepting either Text or InStream.
The result is a working file with correct content…
procedure WebserviceCall(var ResponseInStream: InStream): Text
var
...
begin
//File Downloads using HttpClient
//WebClient call downloading a file
//...
//Check response headers to decide how to proceed
ResponseMessage.Content.GetHeaders(ResponseHeader);
ResponseHeader.GetValues('Content-Type', ResponseHeaders);
case ResponseHeaders[1] of
'application/pdf', 'application/octet-stream':
begin
//Store response stream directly
ResponseMessage.Content.ReadAs(ResponseInStream);
exit;
end;
else
ResponseMessage.Content.ReadAs(ResponseText);
end;
//Otherwise return response as text
exit(ResponseText);
end;
Now you could directly proceed using the InStream… This might be persisting in a Blob field or downloading it to the client using DownloadFromStream(…)