开发者社区> 问答> 正文

如何使用云相册中的Java SDK获取照片列表

以下为获取照片列表的完整代码,以展示SDK的使用方式。为了更好理解示例代码,请首先阅读 同步数据一文。 import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.cloudphoto.model.v20170711.ListPhotosRequest;
import com.aliyuncs.cloudphoto.model.v20170711.ListPhotosResponse;
import com.aliyuncs.cloudphoto.model.v20170711.ListPhotosResponse.Photo;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse.Credentials;
public class ListPhotosDemo {
    public static void main(String[] args) throws ClientException {
        // 从您的业务服务器处获取到临时访问凭证和其他访问云相册的信息
        Credentials credentials = getCredentialFromServer();
        String storeName = "<your_photo_store_name>";
        String cloudPhotoRegion = "cn-shanghai";
        // Step1: 创建DefaultAcsClient对象
        DefaultProfile profile = DefaultProfile.getProfile(cloudPhotoRegion, credentials.getAccessKeyId(),
            credentials.getAccessKeySecret(), credentials.getSecurityToken());
        DefaultAcsClient acsClient = new DefaultAcsClient(profile);
        // Step2: 从老数据开始分批获取照片数据
        String cursor = "0";
        List<Long> photoIds = new ArrayList<Long>();
        while (!"EOF".equalsIgnoreCase(cursor)) {
            ListPhotosRequest request = new ListPhotosRequest();
            request.setStoreName(storeName);
            request.setCursor(cursor);
            request.setDirection("forward");
            // 只获取正常状态的照片,每批10条数据。
            request.setState("active");
            request.setSize(10);
            // Step3: 发送请求并接收响应,如果没有抛异常则表示请求成功
            ListPhotosResponse response = acsClient.getAcsResponse(request);
            List<Photo> photos = response.getPhotos();
            for (ListPhotosResponse.Photo photo : photos) {
                photoIds.add(photo.getId());
            }
            // 服务端返回获取下一批数据的游标,调整游标开始获取下一批数据。
            cursor = response.getNextCursor();
        }
        System.out.println("Total PhotoId count = " + photoIds.size());
    }
}


如上述示例代码所示,使用SDK可以快速接入智能云相册。

  1. 构建DefaultAcsClient对象时需要先从您的业务服务器处获取STS凭证,在STS凭证有效期内可以重用这一对象。
  2. 构建请求Request对象,需要根据不同功能提供相应的参数,发送请求就是一个方法调用,参数加签和网络请求发送都由SDK来处理。
  3. 最后是读取和解析响应,需要根据不同的功能做不同的处理。

展开
收起
云栖大讲堂 2017-10-27 13:10:25 1781 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载