+ Start a Discussion
Li WangLi Wang 

How to use HTTP CALLOUT on a .csv document?

Hi,
I have a url which refers to a .csv file. That means if you put the url into your browser, you will download a .csv file.
But how can I use http callout to directly get the content of the .csv file?
I have tried httpresponse, but it does not work. I think it is because httpresponse can only parse Json or xml.
Thanks!
 
Amy HerzAmy Herz

First, make sure to put your endpoint in your remote settings so that Salesforce allows the callout. Then here is some code for a very simple POC I did for the same thing! My endpoint also was a direct link to download the CSV, using it like this as a GET allowed me to parse the CSV and use for record data.

HttpRequest req = new HttpRequest();
req.setHeader('Content-Type', 'application/csv');   
// test CSV has been uploaded and exposed here
req.setEndpoint('your-endpoint-here-as-string');
req.setMethod('GET');
req.setTimeout(60000); 

Http h = new Http();
HttpResponse res = h.send(req);
System.debug('res: ' + res.getBody());
Blob csvBlob = res.getBodyAsBlob(); 
String csvString = csvBlob.toString();

String[] csvLines = csvString.split('\n');
System.debug('csvLines: ' + csvLines);

List<Lead> leads = new List<Lead>();

for(String line : csvLines) {
    System.debug('line: ' + line);
    Lead l = new Lead();
    String[] csvRecordData = line.split(',');
    //csvRecordData[0] != null ? l.id = csvRecordData[0] : null;
    l.firstName = csvRecordData[1];
    l.lastName = csvRecordData[2];
    l.email = csvRecordData[3];
    l.status = csvRecordData[4];
    l.phone = csvRecordData[5];
    l.leadSource = csvRecordData[6];
    l.company = 'testCo';   // forgot to add this col to csv
    leads.add(l);
}

if(!leads.isEmpty()) {
    leads.remove(0);    // first line of CSV is just headers, not a valid lead
    System.debug('leads: ' + leads);
    insert leads;
}