I am trying to upload a JSON file to amazon s3 bucket. But I am getting an exception as : Callout Exception: Unexpected end of file from server
My Code :
public class ProductAmazon_RestClass {
public void ProductAmazon_RestMethod(string folderName){
string binaryString = ProductAmazonIntegration.ProductAmazonIntegration();
String key=’***********************’;
String secret=’*********************************************************************’;
String formattedDateString= Datetime.now().formatGMT(‘EEE, dd MMM yyyy HH:mm:ss z’);
String bucketname ='MyBucket';
String host = ‘s3-website-us-east-1.amazonaws.com’;
String method = ‘PUT’;
String filename = ‘Product/Product.json’;
//Request starts
HttpRequest req = new HttpRequest();
req.setMethod(method);
req.setEndpoint(‘https://’ + bucketname + ‘.’ + host + ‘/’ + bucketname + ‘/’ + filename);
req.setHeader(‘Host’, bucketname + ‘.’ + host);
req.setTimeout(120000);
req.setHeader(‘Content-Length’, string.valueOf(binaryString.length()));
req.setHeader(‘Content-Encoding’, ‘UTF-8’);
req.setHeader(‘Content-type’, ‘application/json’);
req.setHeader(‘Connection’,’keep-alive’);
req.setHeader(‘Date’, formattedDateString);
req.setHeader(‘ACL’,’public-read’);
req.setBody(binaryString);
String stringToSign = ‘PUT\n\n\n’+formattedDateString+’\n\n/’+bucketname+’/’+filename;
String signed = createSignature(stringToSign,secret);
String authHeader = ‘AWS’ + ‘ ‘ + key + ‘:’ + signed;
req.setHeader(‘Authorization’,authHeader);
Http http = new Http();
try {
//Execute web service call
HTTPResponse res = http.send(req);
System.debug(‘RESPONSE STRING: ‘ + res.toString());
System.debug(‘RESPONSE STATUS: ‘+res.getStatus());
System.debug(‘STATUS_CODE: ‘+res.getStatusCode());
} catch(System.CalloutException e) {
system.debug(‘AWS Service Callout Exception: ‘ + e.getMessage());
}
}
public string createSignature(string canonicalBuffer,String secret){
string sig;
Blob mac = Crypto.generateMac(‘HMACSHA1’, blob.valueof(canonicalBuffer),blob.valueof(secret));
sig = EncodingUtil.base64Encode(mac);
return sig;
}
}