java - AWS 签名 URL 可在除 Android 以外的任何地方使用

标签 java android amazon-web-services aws-lambda

我正在使用 AWS Lambda 为我的移动产品创建一个简单的上传服务。

在服务器上,我使用以下代码生成一个预签名 URL

var params = {
    Bucket: targetS3Bucket,
    Key: key,
    Body: '',
    ContentType: event.contentType,
    Expires: 60
};

s3.getSignedUrl('putObject', params, function (err, url){
    context.done(null, {
        'oneTimeUploadUrl': url,
        'resultUrl': urlPrefix + key
    });
});

其中 targetS3Bucket 是 S3 上文件夹的路径,key 是文件本身的名称,urlPrefix 是根目录S3 上文件的 HTTP 位置(即:s3.amazonaws.com/some-folder/)

将此代码与内置 HTTP 库(也就是说,不使用任何 aws SDK)一起使用可以在 PC 和 iOS 上正常运行,但不能在 Android 上运行。

最新版本的 Android 客户端代码如下所示:

uri = new URL(oneTimeUploadUrl);

// Setup Connection
HttpsURLConnection http = (HttpsURLConnection) uri.openConnection();
http.setDoOutput(true);
http.setRequestMethod("PUT");
​
// Write Data
OutputStream os = http.getOutputStream();
os.write(_bytes);
os.flush();
os.close(); // request gets sent off to the server

这始终失败,代码为 400。我尝试了几种方法,例如更改编码、使用 HttpsURLConnection 的非 https 版本以及其他一些方法,但都无济于事。

我宁愿避免引入 AWS SDK,因为我只需要这个单一功能即可工作,并且使用这个 lambada 端解决方案可以在除 android 之外的所有平台上实现这一点。

这是从 AWS 返回的 XML。返回的消息令人困惑,因为客户端从不更改 token ,并且相同的过程在其他设备上成功。

<?xml version="1.0" encoding="UTF-8"?>
<Error>
    <Code>InvalidToken</Code>
    <Message>The provided token is malformed or otherwise invalid.</Message>
    <Token-0>{Token-0}</Token-0>
    <RequestId>{RequestId}</RequestId>
    <HostId>{HostId}</HostId>
</Error>

最佳答案

问题是 HttpURLConnection 默默地将 Content-Type: application/x-www-form-urlencoded 添加到请求中。这很烦人,因为确定 HttpURLConnection 对象的请求中包含哪些 header 并不容易。

无论如何。这是正确的代码

uri = new URL(oneTimeUploadUrl);

// Setup Connection
HttpsURLConnection http = (HttpsURLConnection) uri.openConnection();
http.setDoOutput(true);
http.setRequestMethod("PUT");
http.setRequestProperty("Content-Type"," "); // remove Content-Type header

// Write Data
OutputStream os = http.getOutputStream();
os.write(_bytes);
os.flush();
os.close(); // request gets sent off to the server

另请参阅:HttpURLConnection PUT to Google Cloud Storage giving error 403

关于java - AWS 签名 URL 可在除 Android 以外的任何地方使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36414649/

相关文章:

java - 如何克服 LWUIT 中的 RecordStoreFullException 错误?

安卓工作室模拟器 : Setting cellular signal strength to "none" still allows network traffic to go through

android - 如何使 Android 上的 NanoHTTPD 接受来自具有专用客户端证书的客户端的连接

Python:如何从AWS S3读取和加载Excel文件?

java - 用我自己的字符串覆盖 string.xml

java - X.jar 中的 Maven JarClassLoader : Warning:Foo. 类被 Y.jar 隐藏(具有不同的字节码)

java - 在动态 Web 项目中使用 m2e 插件

android - 保护安卓设备

node.js - 仅使用插入配置 DynamoDB 流触发器

amazon-web-services - 如何确认对 aws SNS 主题的松弛订阅?