Monday, November 17, 2014

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

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();
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();
Blob fileContentAsBlob = request.getBodyAsBlob();

The last thing to do is to enable your instance URL from Setup > Remote Site Settings, allowing but also I suggest 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).

No comments:

Post a Comment