Java – Android HttpURLConnection PUT to Amazon AWS S3 403 error

Android HttpURLConnection PUT to Amazon AWS S3 403 error… here is a solution to the problem.

Android HttpURLConnection PUT to Amazon AWS S3 403 error

Upload a file

to Amazon S3 using a presigned URL with a signature, expiration time, and access key, with the following code I can upload a file using normal Java code, but the same code in Android gives me a 403 error. Use the Amazon SDK to generate presigned URLs

I have read http://developer.android.com/reference/java/net/HttpURLConnection.html
and http://android-developers.blogspot.com/2011/09/androids-http-clients.html but can’t figure out what header parameter I should use, I guess in android it’s setting headers in requests that the server rejects

    HttpURLConnection connection=(HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT"); 
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    out.write("This text uploaded as object.");
    out.close();
    int responseCode = connection.getResponseCode();

Exception: 403; signature mismatch: -o

Has anyone encountered this issue?
Or more details, which header parameters were added behind the scenes of the android library?

Solution

Set your content type like this:

connection.setRequestProperty("Content-Type"," ");

Because HttpsUrlConnection automatically generates the content type by default:

"Content-Type: application/x-www-form-urlencoded"

This results in a signature mismatch.

Related Problems and Solutions