When Salesforce is life!

[Salesforce / Apex] Retrieving zipped static resource files from code

Spread the love

Some days ago one of my awesome colleagues asked me: “Can you get a zipped file into a static resource from Apex?”.
My very first thought was NO.

But after having said that syllable, I understood that this could be possible, using an HTTP GET call + cookies + correct resource URL.

This is the solution I came into:

Http h = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'resource/ZIPPEDRESOURCE/file.ext');
request.setMethod('GET');
request.setHeader('Cookie','sid='+UserInfo.getSessionId()+';');
request.setTimeout(60000);
HttpResponse request = h.send(request);
if(request.getStatusCode() != 200){
    //handle the error
    throw new CustomException('Unable to load resource');    
}
//now you can get the content
String fileContent = request.getBody();
//or
Blob fileContentAsBlob = request.getBodyAsBlob();

The last thing to do is to enable your instance URL from Setup > Remote Site Settings, allowing https://xxx.salesforce.com but also I suggest https://c.xxx.visual.force.com and wathever it makes sense (there could be some URL path I haven’t though to).

No surprise that this could be used to get any resource in the CRM (with the proper URL handling).

Previous

[-1 to #TCO14] – TCO14 for Dummies

Next

TCO14 (My) Chronicles

2 Comments

  1. shu

    Getting following response :
    System.HttpResponse[Status=Moved Temporarily, StatusCode=302]

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Powered by WordPress & Theme by Anders Norén