0

I am making third party api call from Apex using below piece of code:-

HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setBody(Body); 
req.setHeader('Content-Type', 'application/pdf');  
req.setTimeout(120000);
HttpResponse res = new HttpResponse();
Http http = new Http();
res = http.send(req);

I am getting response body as Byte[] from the third party system. I am stuck parsing it and saving as contentversion file in Salesforce. The response format is:-

%PDF-1.7
%����
1 0 obj
<</Type/Catalog/Pages 2 0 R/Lang(en-IN) /StructTreeRoot 33 0 R/MarkInfo<</Marked true>>/Metadata 360 0 R/ViewerPreferences 361 0 R>>
endobj
2 0 obj
<</Type/Pages/Count 3/Kids[ 3 0 R 28 0 R 30 0 R] >>
endobj
3 0 obj
<</Type/Page/Parent 2 0 R/Resources<</Font<</F1 5 0 R/F2 9 0 R/F3 11 0 R/F4 16 0 R/F5 18 0 R/F6 23 0 R>>/ExtGState<</GS7 7 0 R/GS8 8 0 R>>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/MediaBox[ 0 0 595.32 841.92] /Contents 4 0 R/Group<</Type/Group/S/Transparency/CS/DeviceRGB>>/Tabs/S/StructParents 0>>
endobj
4 0 obj
<</Filter/FlateDecode/Length 4852>>
stream
x���r۸�=3�<J��K����c;��n��I��m���ȲW�............................................................................................................................................0000148859 00000 n
trailer
<</Size 363/Root 1 0 R/Info 32 0 R/ID[<8BB3C37689ABB6438887215505D395FB><8BB3C37689ABB6438887215505D395FB>] >>
startxref
149843
%%EOF
xref
0 0
trailer
<</Size 363/Root 1 0 R/Info 32 0 R/ID[<8BB3C37689ABB6438887215505D395FB><8BB3C37689ABB6438887215505D395FB>] /Prev 149843/XRefStm 148859>>
startxref
157263
%%EOF

What I have tried?

  1. https://developer.salesforce.com/forums/?id=9062I000000Xz1sQAC
  2. https://dfc-org-production.force.com/forums/ForumsMain?id=906F00000008zfhIAA
  3. How to attach pdf file represented as bytes(response from SOAP API) to an Opportunity?
  4. Perform Callout, get byte[] and view pdf
  5. Convert Byte Array/JSONArray to Base 64 String via APEX

1 Answer 1

4

You don't need to do anything special, just get the body's Blob content:

Blob fileContent = res.getBodyAsBlob();
ContentVersion cv = new ContentVersion(VersionData=fileContent);
// Don't forget the other fields...
insert cv;
2
  • Thanks a lot @sfdcfox, You are always a savior, It worked perfectly fine. Additionally, Will it fail if the file size is large than heap size limit? How to handle those situation? Jul 19, 2022 at 5:21
  • @sanketkumar Yes, a callout will fail if the original response is larger than the heap size limit. It will fail at the line httpresponse res = new http().send(req); You cannot handle that situation in Apex, you'd need to use some other technology.
    – sfdcfox
    Jul 19, 2022 at 13:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .