Search code examples
javacurlapache-commons-httpclient

Curl to Java httpclient


I have curl command:

curl -s -T '/orig.jpg' -H 'content-type:image/jpeg' 'https://amazonaws.com/d5OCmmq-MgbIPk6ZRqql4bZX3gZ2QhG8uum6YDdcZYcRtohs3ZIMxF1gR3rFcPEg1-Vz-v8hUuKATM6D_-FrtQ%3D%3D/orig.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJGCZOCB2ULPVHGAA%2F20160416%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20160416T202457Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=2dcfb2b843d484e50557d2da430e60512a49070bed219ae98970284ef735e02e'

It is works fine. Then I want do the same but with httpclient:

File file = new File(imagePath);
HttpPost post = new HttpPost(url);
post.setHeader(HTTP.CONTENT_TYPE, "image/jpeg");
ContentBody fileBody = new FileBody(file, ContentType.create("image/jpeg"));

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("orig.jpg", fileBody);
HttpEntity entity = builder.build();

post.setEntity(entity);
HttpResponse response = periscope.getClient().execute(post);

Response:

SignatureDoesNotMatch. The request signature we calculated does not match the signature you provided. Check your key and signing method.


Solution

  • curl -T/--upload-file uses PUT (unless you specify -X/--request) not POST, although the server apparently doesn't care because it would typically complain about method before content; and it sends a single entity not mislabelled multipart as your Java does. Try using a plain FileEntity. Also it can set content-type automatically, you don't need to. Specifically:

    HttpPost post = new HttpPost(url); // or maybe Put
    post.setEntity (new FileEntity (file, ContentType.create("image/jpeg")));
    ... client.execute(post);