You are on page 1of 7

Chat GPT Question:

can you give me an example for apex code integration (without using any other client, directly
between Salesforce and SFTP)

ANSWER
public class SFTPIntegration {

public static void transferFile() {

String username = 'your_username';

String password = 'your_password';

String server = 'sftp.yourserver.com';

Integer port = 22;

String path = '/path/to/remote/file.txt';

String localPath = 'file.txt';


String ftpCommand = 'GET ' + path;

HttpRequest req = new HttpRequest();

req.setMethod('GET');

req.setEndpoint('callout:SFTP/' + server + ':' + port);

req.setHeader('Content-Type', 'text/plain');

req.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' +


password)));

req.setBody(ftpCommand);

req.setTimeout(120000);

Http http = new Http();

HttpResponse res = http.send(req);

if (res.getStatusCode() != 200) {

System.debug('Failed to transfer file. Status code: ' + res.getStatusCode() + ', message: ' +
res.getStatus());

} else {

Blob fileContent = res.getBodyAsBlob();

String fileAsString = fileContent.toString();

// do something with the file content, such as insert into a custom object

Attachment attachment = new Attachment();

attachment.Name = 'file.txt';

attachment.Body = fileContent;

attachment.ParentId = 'your_record_id';

insert attachment;

}
SFTPIntegration.transferFile();
public class SFTPIntegration {

public static void transferFile() {

String username = 'your_username';

String password = 'your_password';

String server = 'sftp.yourserver.com';

Integer port = 22;

String path = '/path/to/remote/file.txt';


String localPath = 'file.txt';

String ftpCommand = 'GET ' + path;

HttpRequest req = new HttpRequest();

req.setMethod('GET');

req.setEndpoint('https://' + server + ':' + port);

req.setHeader('Content-Type', 'text/plain');

req.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(username + ':' +


password)));

req.setBody(ftpCommand);

req.setTimeout(120000);

Http http = new Http();

HttpResponse res = http.send(req);

if (res.getStatusCode() != 200) {

System.debug('Failed to transfer file. Status code: ' + res.getStatusCode() + ', message: ' +
res.getStatus());

} else {

Blob fileContent = res.getBodyAsBlob();

String fileAsString = fileContent.toString();

// do something with the file content, such as insert into a custom object

Attachment attachment = new Attachment();

attachment.Name = 'file.txt';

attachment.Body = fileContent;

attachment.ParentId = 'your_record_id';

insert attachment;

}
}

You might also like