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
dinesh sivalingamdinesh sivalingam 

Download a file from a url using apex class

Hi

I have a url which contains xml file, if i click the click the url it will download the file to my local drive, instead of doing it manually i need to achieve this using apex class, i.e. the scheduled apex class download the file from a url and upload it to the custom object.

How to achieve this, anybody have worked this kind of scenario.

thanks
Dinesh
 
EnreecoEnreeco
Hi Dinesh, does the URL needs some sort of authentication or it is an accessible resource?
If it is free to use by anyone, you can simply do something like this:
// Instantiate a new http object
Http h = new Http();
// Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
HttpRequest req = new HttpRequest();
req.setEndpoint('YOUR_URL');
req.setTimeout(60000);//sets maximum timeout
req.setMethod('GET');
// Send the request, and return a response
HttpResponse res = h.send(req);
Blob body = res.getBodyAsBlob();
//then you can attach this body wherever you want
Attachment att = new Attachment(Name = 'SET A NAME', Body = body, ContentType = 'SET A VALID CONTENT TYPE', ParentId='PARENT_OBJ_ID');
insert att;
Remember to add the proper Remote Site Setting (Setup > Security controls > Remote Site Settings > Add your server)
--
May the Force.com be with you!
sarath reddysarath reddy

Hi Dinesh, 

Is this worked for you?

its attaching the response as blob and attching to the record. not the content in the URL is attched to the record.
For me, when i click on the URL, a file is download and I need to add the PDF to the record as attachment. 

please share your thoughts.

Regards
Sarath M

Carlos Carvalho JrCarlos Carvalho Jr
Try to do this

Pagereference pg = new Pagereference(YOUR_URL);
Blob b = pg.getContentAsPDF();
//Example to save PDF
Attachment att = new Attachment(Name = 'stvm_4', Body = b, ContentType = 'application/pdf', ParentId='Sobject_Id');
Shubham Deshmukh 15Shubham Deshmukh 15

Hi,

What if the content is other than pdf like docx, voice recording. How to insert into custom object attachments.

Any help will be appreciated