[SalesForce] Sharepoint Integration From Apex

We need to upload files to sharepoint and able to view the uploaded files to sharepoint in salesforce. So we cant achieve this in File Connect, where it is not supporting two way synchronisation.

So im trying to achieve this from Apex using REST API, I'm able to get the access token, able to get the list of files and folders from Sharepoint.

When i try to upload files into sharepoint, im getting response like this:

[Status=Bad Request, StatusCode=400]

But when i try to upload the files using Postman i can able to upload it.

HttpRequest httpRequestToSend = new HttpRequest();  

httpRequestToSend.setEndpoint('https://testsharepoint.sharepoint.com/sites/testsite/_api/web/GetFolderByServerRelativeUrl(\''+'/sites/testsite/Shared Documents/Test 1'+'\')/files/add(url=\''+'document3.txt'+'\', overwrite=true)');
httpRequestToSend.setMethod('POST');
httpRequestToSend.setHeader('Authorization', 'Bearer ' + access_token);
httpRequestToSend.setHeader('Content-Type','application/json;odata=verbose');

//httpRequestToSend.setBody('test message');
httpRequestToSend.setBodyAsBlob(Blob.ValueOf('test Message'));

System.debug('***** httpRequestToSend-->' + httpRequestToSend);

Http http = new Http();   
HttpResponse httpResponse = http.send(httpRequestToSend);  
System.debug('***** httpResponse-->' + httpResponse);

I'm able to get the access token, able to the list of files and folders. I was wondering why it's only happening for file upload, i checked with permissions as well while registering the app in sharepoint

I'm referring this blog, i didnt found any proper documentation related to sharepoint integration from apex

Any suggestions/ideas are much appreciated

Best Answer

Finally after i spent 6 hours with more patience, i figured it out whats been causing the issue, In the end point there is space between the folder names, so some how postman managed that to encode the string and sending it, but salesforce is not encoding that

Prev Code:

httpRequestToSend.setEndpoint('https://testsharepoint.sharepoint.com/sites/testsite/_api/web/GetFolderByServerRelativeUrl(\''+'/sites/testsite/Shared Documents/Test 1'+'\')/files/add(url=\''+'document3.txt'+'\', overwrite=true)');

It should be like this:

httpRequestToSend.setEndpoint('https://testsharepoint.sharepoint.com/sites/testsite/_api/web/GetFolderByServerRelativeUrl(\''+'/sites/testsite/Shared%20Documents/Test%201'+'\')/files/add(url=\''+'document3.txt'+'\', overwrite=true)');

This works for me. Thanks.