安装依赖
在Android Studio环境中添加如下依赖:
dependencies { compile 'com.aliyun.dpa:oss-android-sdk:2.9.11' }
简单上传
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
OSSCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {
@Override
public String signContent(String content) {
URL stsUrl = new URL("http://localhost:8080/sign?content=" + content);
HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
InputStream input = conn.getInputStream();
String jsonText = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
JSONObject jsonObjs = new JSONObject(jsonText);
String signature = jsonObjs.getString("signature");
return signature;
}
};
OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
PutObjectRequest put = new PutObjectRequest("examplebucket", "exampledir/exampleobject.txt", "/storage/emulated/0/oss/examplefile.txt");
try {
PutObjectResult putResult = oss.putObject(put);
Log.d("PutObject", "UploadSuccess");
Log.d("ETag", putResult.getETag());
Log.d("RequestId", putResult.getRequestId());
} catch (ClientException e) {
// 客户端异常,例如网络异常等。
e.printStackTrace();
} catch (ServiceException e) {
// 服务端异常。
Log.e("RequestId", e.getRequestId());
Log.e("ErrorCode", e.getErrorCode());
Log.e("HostId", e.getHostId());
Log.e("RawMessage", e.getRawMessage());
}
遇到的问题
签名计算失败
The request signature we calculated does not match the signature you provided.
签名计算失败,大概有几种可能
- 自有服务端
AccessKeyId
或者AccessKeySecret
错误 - 客户端
OSSCustomSignerCredentialProvider
上传的content
的内容问题 - 自有服务器返回的内容
signature
错误
第一种可能:使用AccessKeyId
和AccessKeySecret
登录阿里云OSS
就可以验证
第二种可能:客户端上传content
内容本身没有问题,但是通过自有服务端接口,使用GET
方法上传content
时,自有服务端接收到的content
并不包含\n
,从而返回的signature
就有问题,客户端可以在上传content
时,对content
进行base64编码,自有服务端接收到数据后,再进行解码
OSSCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {
@Override
public String signContent(String content) {
String base64Content = BinaryUtil.toBase64String(content.getBytes(StandardCharsets.UTF_8));
URL stsUrl = new URL("http://localhost:8080/sign?content=" + base64Content);
HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
InputStream input = conn.getInputStream();
String jsonText = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
JSONObject jsonObjs = new JSONObject(jsonText);
String signature = jsonObjs.getString("signature");
return signature;
}
};
第三种可能:自有服务端收到content
后,计算错误
正确签名格式如下
signature = "OSS " + AccessKeyId + ":" + base64(hmac-sha1(AccessKeySecret, content))
如果使用的是阿里云提供的类HmacSHA1Signature
来签名时,需要注意computeSignature
方法中已经进行过base64编码,所以不需要再进行一次base64编码
signature = "OSS " + AccessKeyId + ":" + new HmacSHA1Signature().computeSignature(AccessKeySecret, content)