我们有 iOS 和 Android 应用程序可以为 s3 下载文件。由于我们拥有全球客户,因此我们希望迁移到 CloudFront。
我知道为了做到这一点,我需要从 / 构造一个 url 并发送 NSURLRequest。这意味着我不再使用专用的 S3GetObjectRequest 从存储桶中获取对象。
我想知道这是否是唯一的方法,还是有办法使用 cloudFront 处理 s3 类?
这是我的代码(iOS):
- (int) request:(NSString*)request response:(NSData**)response
{
NSInteger httpStatus = 0;
NSData* theData = NULL;
NSString* cloudFrontDomain = [self cloudFrontDomain];
if(cloudFrontDomain){
NSString *urlString = [cloudFrontDomain stringByAppendingPathComponent: request];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSError *error = nil;
NSHTTPURLResponse *httpResponse = nil;
theData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&httpResponse error:&error];
httpStatus = [httpResponse statusCode];
}
else{
NSString* bucket = [self s3BucketName];
S3GetObjectRequest* s3Request = [[S3GetObjectRequest alloc] initWithKey: request withBucket:bucket];
S3GetObjectResponse* s3Response = [s3Service getObject:s3Request];
theData = [s3Response body];
httpStatus = [s3Response httpStatusCode];
[s3Request release];
}
if (httpStatus == 200) {
*response = [[NSData alloc] initWithData:theData];
}
return httpStatus;
}
安卓:
byte[] request(String key) {
String cloudFrontDomain = getCloudFrontDomain();
if (cloudFrontDomain != null){
try {
String url = cloudFrontDomain + "/" + key;
URL myFileURL = new URL(url);
InputStream response = myFileURL.openStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(response, outputStream);
return outputStream.toByteArray();
} catch ... {
....
}
}
else{
String bucket = getS3BucketName();
GetObjectRequest request = new GetObjectRequest(bucket, key);
try {
S3Object response = s3Service.getObject(request);
if (null != response){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(response.getObjectContent(), outputStream);
return outputStream.toByteArray();
}
else {
return null;
}
}catch ... {
...
}
}
}