简体   繁体   English

无法使用http put将图像上传到Amazon s3

[英]Cannot upload image to amazon s3 using http put

I am developing an Android app, where users can create posts with images. 我正在开发一个Android应用,用户可以在其中创建带有图像的帖子。 Images are uploading to Amazon S3. 图像正在上传到Amazon S3。 So how every user can upload an image, I dont use Amazon AWS SDK, because its methods need secret key. 因此,每个用户如何上传图像,我不使用Amazon AWS开发工具包,因为其方法需要密钥。 I try to upload an image using HTTP put request. 我尝试使用HTTP put请求上传图像。 I send first request to backend, and it sends to me signature and other paramrters which is use to upload an image. 我向后端发送了第一个请求,它向我发送了用于上传图像的签名和其他参数。 Unfortunately the second response from amazon contains error. 不幸的是,亚马逊的第二个回应包含错误。

Here is the first request and response: 这是第一个请求和响应:

POST /upload HTTP/1.1
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 53
Host: wrum-wrum.ru
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)

file_name=1439474973659_crp.jpg&file_type=image%2Fjpg


HTTP/1.1 200 OK
Server: nginx
Date: Thu, 13 Aug 2015 14:09:46 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Keep-Alive: timeout=60
Vary: X-HTTP-Method-Override
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Download-Options: noopen
set-cookie: connect.sid=s%3AY0SlTYzkavxu34-pcuMIEGDPuRSDlKuM.%2FTRySP3UVyIIatnqLSGE8%2Bx%2BP239TL9rjPQxjVRbzD8; Path=/; HttpOnly

11b
{"signed_request":"https://babadoo.s3.amazonaws.com/1439474973659_crp.jpg?AWSAccessKeyId=AKIAJMXM46BCWD5WDGTQ&Content-Type=image%2Fjpg&Expires=1439475046&Signature=ZsqF%2BaCCeZmTTPkiTWLG5Ckix1U%3D&x-amz-acl=public-read","url":"https://babadoo.s3.amazonaws.com/1439474973659_crp.jpg"}
0

Here is the second request and response: 这是第二个请求和响应:

PUT /1439474973659_crp.jpg?AWSAccessKeyId=AKIAJMXM46BCWD5WDGTQ&Content-Type=image%2Fjpg&Expires=1439475046&Signature=ZsqF%2BaCCeZmTTPkiTWLG5Ckix1U%3D&x-amz-acl=public-read HTTP/1.1
Content-Type: image/jpeg
User-Agent: Apache-HttpClient/UNAVALIABLE (java 1.4)
Content-Length: 1242599
Host: babadoo.s3.amazonaws.com
Connection: Keep-Alive
Expect: 100-continue

HTTP/1.1 403 Forbidden
x-amz-request-id: 36D4D3E461AF0850
x-amz-id-2:     +/LpGcZD6ZMdbZDq31Zt5ablP5CZIbBElaD1pm6of7MrndAwXe6ortO3uJNVgn8sGQ03o2waie0=
Content-Type: application/xml
Transfer-Encoding: chunked
Date: Thu, 13 Aug 2015 14:10:00 GMT
Connection: close
Server: AmazonS3

357
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>AKIAJMXM46BCWD5WDGTQ</AWSAccessKeyId><StringToSign>PUT

image/jpeg
1439475046
x-amz-acl:public-read
/babadoo/1439474973659_crp.jpg</StringToSign><SignatureProvided>ZsqF+aCCeZmTTPkiTWLG5Ckix1U=</SignatureProvided><StringToSignBytes>50 55 54 0a 0a 69 6d 61 67 65 2f 6a 70 65 67 0a 31 34 33 39 34 37 35 30 34 36 0a 78 2d 61 6d 7a 2d 61 63 6c 3a 70 75 62 6c 69 63 2d 72 65 61 64 0a 2f 62 61 62 61 64 6f 6f 2f 31 34 33 39 34 37 34 39 37 33 36 35 39 5f 63 72 70 2e 6a 70 67</StringToSignBytes><RequestId>36D4D3E461AF0850</RequestId><HostId>+/LpGcZD6ZMdbZDq31Zt5ablP5CZIbBElaD1pm6of7MrndAwXe6ortO3uJNVgn8sGQ03o2waie0=</HostId></Error>
0

Code: 码:

public String uploadPhoto(final File file) {


    Runnable runnable = new Runnable() {
        public void run() {


            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(uploadURL);

            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            String result = null;

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("file_name", file.getName()));
                nameValuePairs.add(new BasicNameValuePair("file_type", "image/jpg"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity);
                int i = 1;

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
            if (result != null) {
                int putURLpos = result.indexOf(parseStringFragment);
                if (putURLpos != -1) {
                    putURL = result.substring(putURLpos + parseStringFragment.length(),
                            result.indexOf("\"", putURLpos + parseStringFragment.length()));

                    try {

                        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                        trustStore.load(null, null);

                        SSLSocketFactory sf = (new MySSLSocketFactory(trustStore));
                        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                        BasicHttpParams httpParams = new BasicHttpParams();
                        HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
                        HttpProtocolParams.setContentCharset(httpParams, HTTP.DEFAULT_CONTENT_CHARSET);
                        HttpProtocolParams.setUseExpectContinue(httpParams, true);

                        SchemeRegistry sr = new SchemeRegistry();
                        sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                        sr.register(new Scheme("https", sf, 443));
                        ThreadSafeClientConnManager ccManager = new ThreadSafeClientConnManager(httpParams, sr);

                        HttpClient client = new DefaultHttpClient(ccManager, httpParams);

                        URI uri = new URI(putURL);
                        HttpPut put = new HttpPut(uri);
                        put.setHeader("Content-Type", "image/jpeg");
                        put.setHeader("User-Agent", "Apache-HttpClient/UNAVALIABLE (java 1.4)");

                        EntityBuilder eb = EntityBuilder.create();
                        eb.setFile(file);
                        put.setEntity(eb.build());
                        HttpResponse response = client.execute(put);


                        HttpEntity resEntity = response.getEntity();
                        String res = EntityUtils.toString(resEntity);

                        int i = 1;
                        i++;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return uploadedPhotoURL;
}

So I find the solution. 所以我找到了解决方案。 It was my fault, I sent 是我的错,我发了

nameValuePairs.add(new BasicNameValuePair("file_type", "image/jpg"));

for the first request, and 对于第一个请求,并且

Content-Type: image/jpeg

in the second request. 在第二个请求中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM