[SalesForce] handle PDF content in HTTP callout

I am making a callout to a third party and response is a PDF file. However, on salesforce side seems like PDF is getting corrupted.Seems like method "getBodyAsBlob" does not work.

HTTP h = new HTTP();
    HTTPRequest request = new HTTPRequest();
    request.setEndpoint('endpoint');
    request.setHeader('contentType', 'application/json');
    request.setMethod('GET');
    string str = 'payload';
    request.setBody(JSON.serialize(str));
    HTTPResponse resp = h.send(request); 
    if(resp.getStatusCode()==200){ 
    blob response = resp.getBodyAsBlob();
    Attachment attach = new Attachment();
    attach.contentType = 'application/octet-stream';
    attach.name = 'myfile111.pdf';
    attach.parentId = '001XXXXXXX';
    attach.body = response; //blob.ValueOf(response);
    insert attach;

Could anyone suggest the best way to resolve this?

Best Answer

Assuming they are sending a Base64 string, you then have to use EncodingUtil to decode a base 64 file to blob.

EncodingUtil.base64Decode("base64String");

So your code will be

 HTTP h = new HTTP();
HTTPRequest request = new HTTPRequest();
request.setEndpoint('endpoint');
request.setHeader('contentType', 'application/json');
request.setMethod('GET');
string str = 'payload';
request.setBody(JSON.serialize(str));
HTTPResponse resp = h.send(request); 
if(resp.getStatusCode()==200){ 
    String base64Response = resp.getBody();
    Attachment attach = new Attachment();
    attach.contentType = 'application/octet-stream';
    attach.name = 'myfile111.pdf';
    attach.parentId = '001XXXXXXX';
    attach.body = EncodingUtil.base64Decode(base64Response); 
    insert attach;
}

There won't be any data loss or corruption if they were sending proper base64 string.

Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_encodingUtil.htm