
HttpContent and error checking.local procedure RequestQRCode2(InvoiceJsonData: Text): Text
var
MRsetup: Record LC_MRASetup;
Client: HttpClient;
RequestContent: HttpContent;
Response: HttpResponseMessage;
ResponseText: Text;
JsonResponse: JsonObject;
InvoicesToken: JsonToken;
InvoicesArray: JsonArray;
InvoiceObject: JsonObject;
QRCodeValue: JsonToken;
TempToken: JsonToken;
ReqURL: Text;
begin
if not MRsetup.Get() then Error('MRA Setup not found.');
ReqURL := MRsetup."Invoice Push URL";
RequestContent.WriteFrom(InvoiceJsonData);
RequestContent.GetHeaders().Clear(); // Crucial: Clear existing headers
RequestContent.GetHeaders().Add('Content-Type', 'application/json');
Client.DefaultRequestHeaders().Add('Authorization', 'Bearer ' + MRsetup."Bearer Token");
Client.DefaultRequestHeaders().Add('Accept', 'application/json');
// Check if the HTTP request itself failed
if not Client.Post(ReqURL, RequestContent, Response) then
Error('Failed to send HTTP POST request to middleware.');
// Check middleware response status
if not Response.IsSuccessStatusCode() then begin
Response.Content().ReadAs(ResponseText);
Error('Request failed: %1. Middleware Response: %2', Response.HttpStatusCode(), ResponseText);
end;
Response.Content().ReadAs(ResponseText); // Read successful response
if not JsonResponse.ReadFrom(ResponseText) then
Error('Invalid JSON received from middleware: %1', ResponseText);
if JsonResponse.Get('fiscalisedInvoices', InvoicesToken) and InvoicesToken.IsArray() then begin
InvoicesArray := InvoicesToken.AsArray();
if InvoicesArray.Count > 0 and InvoicesArray.Get(0, TempToken) and TempToken.IsObject() then begin
InvoiceObject := TempToken.AsObject();
if InvoiceObject.Get('qrCode', QRCodeValue) and QRCodeValue.IsText() then
exit(QRCodeValue.AsValue().AsText());
end;
end;
Error('QR code not found in middleware response JSON: %1', ResponseText);
end;
Key Points:
RequestContent.GetHeaders().Clear(): Ensures correct Content-Type by clearing defaults.Client.Post return), then for middleware response status (Response.IsSuccessStatusCode).IsArray() and IsObject() checks for safer parsing.ResponseText on failure for middleware details.