function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ayushi_TiwariAyushi_Tiwari 

How to upload a pdf file to a third party server from apex REST POST callout?

Hello everyone,

I am trying to upload a pdf file to third party server from apex rest POST callout, and getting [Status=Unauthorized, StatusCode=401]. This is working fine in postman with the same session id and endpoint URL But not working in apex. 
The pdf file needs to be set as a body for the callout, how can I achieve this?
VinayVinay (Salesforce Developers) 
Hi Ayushi,

You can send attachments by using HTTP/HTTPS Protocol

Following are the aspects you need to understand while using HTTP Protocol from Client side.

>> Construct the http class and convert  the attachment into base 64 and MIME versions using salesforce utils class methods.
>> Create the connection and send the file.

HttpRequest Class
==============
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_httprequest.htm

Http Class
========
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_http.htm

Sample code snippet:

HttpRequest req = new HttpRequest();
req.setEndPoint('https://your-url.com');
req.setBody('Hello World');

Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());

Send text based file attachment from Salesforce Apex:

String fileName = 'MY_FILE.txt';
String fileContent = 'Hello World';
String targetURL = 'https://your.target.com/api';
String separationString = 'A_RANDOM_STRING';

// assemble the body payload
String header = '--' + separationString + '\nContent-Disposition: form-data; name="file"; filename="' + fileName + '"\nContent-Type: application/octet-stream\n\n';
String body = EncodingUtil.base64Encode(fileContent) + '\n';
String footer = '--' + separationString + '--';
String bodyPayload = header + body + footer;

// send out the request
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'multipart/form-data; boundary=' + separationString);
req.setHeader('Content-Length', String.valueof(bodyPayload));
req.setMethod('POST');
req.setEndpoint(targetURL);
req.setBody(bodyPayload);

Http http = new Http();
http.send(req);

https://salesforce.stackexchange.com/questions/180311/send-blob-file-via-apex-rest-callout
https://docparser.com/blog/post-file-salesforce-apex-external-http-webservices/

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar
Sherry NorvellSherry Norvell
Looking great work dear, I really appreciated to you on this quality These tips may help me for future.
auto clicker (https://mouseclicker.net/)