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.setEndpoint(‘https://’ + bucketname + ‘.’ + host + ‘/’ + bucketname + ‘/’ + filename);
req.setHeader(‘Host’, bucketname + ‘.’ + host);
req.setHeader(‘Content-Length’, string.valueOf(binaryString.length()));
req.setHeader(‘Content-Encoding’, ‘UTF-8’);
req.setHeader(‘Content-type’, ‘application/json’);
req.setHeader(‘Date’, formattedDateString);

String stringToSign = ‘PUT\n\n\n’+formattedDateString+’\n\n/’+bucketname+’/’+filename;
String signed = createSignature(stringToSign,secret);
String authHeader = ‘AWS’ + ‘ ‘ + key + ‘:’ + signed;
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;


This is not correct:

String host = ‘s3-website-us-east-1.amazonaws.com’;

That's a website endpoint, so it will not speak HTTPS and it will not accept PUT requests.

If your bucket is in us-east-1, set this to s3.us-east-1.amazonaws.com. (Formerly, you would have needed to use s3.amazonaws.com or s3-external-1.amazonaws.com, and these are still valid but us-east-1 now also supports the standard convention for REST endpoints.)

This is also not correct.

req.setEndpoint(‘https://’ + bucketname + ‘.’ + host + ‘/’ + bucketname + ‘/’ + filename);

Remove bucketname + ‘/’ + before filename.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.