欢迎您来到腾讯云!积分商城

腾讯云腾讯云论坛

 找回密码
 立即注册
忘了密码?

扫一扫,访问微社区

快捷导航
搜索
查看: 318|回复: 0

[经验分享] AWS-JAVA-SDK 对 COS 兼容的使用指南

[复制链接]

8

主题

0

好友

370

积分

程序猿[LV2]

Rank: 2Rank: 2

云币
950
威望
370
发表于 2017-11-16 16:22:33 |显示全部楼层 |未分类
1.SDK 名称版本:
aws-java-sdk-v1.11.129

2.接口兼容概述
cos 后台有条件兼容了 aws sdk,一般 sdk 需要做以下四个方面的修改,而 java 默认就使用了 virtual style,因此只需要修改下面的1和3部分;
1. 使用 aws v2 签名
2. 使用 virtual style 而非 path style
3. 设置 cos 的 endpoint
4. bucket 名字为 bucket-appid


例如生成一个 aws client 对象的代码如下:
    String sk = "ciivKvnnrMvSvQpMAWuIz12pThGGlWRW";
    String ak = "AKID15IsskiBQKTZbAo6WhgcBqVls9SmuG00";
    BasicAWSCredentials cred = new BasicAWSCredentials(ak, sk);
    ClientConfiguration config = new ClientConfiguration();
    // 设置aws v2签名
    config.setSignerOverride("S3SignerType");
    AmazonS3 s3client = new AmazonS3Client(cred, config);
    // 设置cos的endpoint,以华东(cn-east)举例
    s3client.setEndpoint("cn-east.myqcloud.com");

3.使用示例
3.1.获取 aws-java-sdk-v1.11.129
下载并安装 aws-java-sdk-v1.11.129。
代码路径:
https://github.com/aws/aws-sdk-java

3.2.使用示例
常见功能使用(上传、下载、删除...)
    String sk = "ciivKvnnrMvSvQpMAWuIz12pThGGlWRW";
    String ak = "AKID15IsskiBQKTZbAo6WhgcBqVls9SmuG00";
    BasicAWSCredentials cred = new BasicAWSCredentials(ak, sk);
    ClientConfiguration config = new ClientConfiguration();
    // 设置aws v2签名
    config.setSignerOverride("S3SignerType");
    AmazonS3 s3client = new AmazonS3Client(cred, config);
    // 设置cos的endpoint,以华东(cn-east)举例
    s3client.setEndpoint("cn-east.myqcloud.com");
    String bucketName = "rabbitliush2-1252448703";
    String localPath = "/path/to/file.txt";
    String cosKey = "key";
    String localKeyDonwload = "/path/to/download.txt";
    try {
            createBucket(s3client, bucketName);
            deleteBucket(s3client, bucketName);
            listBucket(s3client, bucketName);
            putObject(s3client, bucketName, localPath, cosKey);
              getObject(s3client, bucketName, cosKey, localKeyDownload);
            deleteSingleObject(s3client, bucketName, key);
            getService(s3client);
        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which " +
                    "means your request made it " +
                    "to Amazon S3, but was rejected with an error response" +
                    " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which " +
                    "means the client encountered " +
                    "an internal error while trying to " +
                    "communicate with S3, " +
                    "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        } catch (Exception e) {
            System.out.println("Caught an Exception: " + e.getMessage());
        }
    }

    private static void createBucket(AmazonS3 s3client, String bucketName)
    throws AmazonServiceException, AmazonClientException {
        if (!s3client.doesBucketExist(bucketName)) {
            s3client.createBucket(new CreateBucketRequest(bucketName));
            System.out.println("create bucket name: " + bucketName);
        }
        System.out.println("bucket name exist: " + bucketName);
    }

    private static void deleteBucket(AmazonS3 s3client, String bucketName)
    throws AmazonServiceException, AmazonClientException {
        s3client.deleteBucket(bucketName);
    }

    private static void listBucket(AmazonS3 s3client, String bucketName)
    throws AmazonServiceException, AmazonClientException {
        ObjectListing objects = s3client.listObjects(bucketName);
        do {
            System.out.println("listing");
                for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                        System.out.println(objectSummary.getKey() + "\t" +
                                objectSummary.getSize() + "\t" +
                                StringUtils.fromDate(objectSummary.getLastModified()));
                }
                objects = s3client.listNextBatchOfObjects(objects);
        } while (objects.isTruncated());
    }

    private static void putObject(AmazonS3 s3client, String bucketName,
                                  String uploadFileName, String keyName) {
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        PutObjectRequest putRequest = new PutObjectRequest(
                 bucketName, keyName, file);
        s3client.putObject(putRequest);
    }

    private static void getObject(AmazonS3 s3client, String bucketName,
                                  String keyName, String localName) {
        System.out.println("Get a object");
        File dst = new File(localName);
        GetObjectRequest getRequest = new GetObjectRequest(bucketName, keyName);
        getRequest.setRange(0, 10);
        getRequest.getMatchingETagConstraints();
        getRequest.withMatchingETagConstraint("\"81043d81ccd3957ddf9b5ee3aec68e9d\"");
        ObjectMetadata meta = s3client.getObject(getRequest, dst);
        System.out.println("Content-Type: "  + meta.getContentType());
    }

    private static void deleteSingleObject(AmazonS3 s3client, String bucketName,
                                           String keyName) {
        s3client.deleteObject(new DeleteObjectRequest(bucketName, keyName));
    }

    private static void getService(AmazonS3 s3client) {
        s3client.setEndpoint("service.cos.myqcloud.com");
        System.out.println("Listing buckets");
        for (Bucket bucket : s3client.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();
        s3client.setEndpoint("cn-south.myqcloud.com");
    }

您需要登录后才可以回帖 登录 | 立即注册
您需要登录后才可以发帖 QQ登录

联系我们|腾讯云平台|积分商城|腾讯云官方论坛    

GMT+8, 2018-5-21 21:03 , Processed in 1.181486 second(s), 29 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部