将 s3 下载从 iOS / Android 应用程序迁移到 CloudFront

2023-12-28

我们有 iOS 和 Android 应用程序可以下载 s3 文件。由于我们拥有全球客户,因此我们希望迁移到 CloudFront。

我知道为了做到这一点,我需要从 / 构造一个 url 并发送 NSURLRequest。这意味着我不再使用专用的 S3 GetObjectRequest 从存储桶获取对象。

我想知道这是否是唯一的方法,或者有没有办法通过 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;
}

Android:

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 ... {
            ...
        }
    }
}

None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 s3 下载从 iOS / Android 应用程序迁移到 CloudFront 的相关文章

随机推荐