UCloud US3 (原名UFile) SDK for Java
Version History
Ver 1.0.0不建议使用
环境要求
- 开发环境: Java 1.8.0_91 或以上
- 运行环境: Java 1.8.0_91 或以上
API Doc
安装
-
Maven
您可以通过在pom.xml中添加以下依赖项,来配置您的Maven项目。添加依赖后,请执行项目刷新(如 IDEA 中点击 Reload Project)以使依赖生效。
1 2 3 4 5 6
<dependency> <groupId>cn.ucloud.ufile</groupId> <artifactId>ufile-client-java</artifactId> <!-- 当前推荐版本 --> <version>2.7.5</version> </dependency>
-
Gradle
1 2 3 4 5 6
dependencies { /* * your other dependencies */ implementation 'cn.ucloud.ufile:ufile-client-java:latest-release-version' }
快速入门
- 基本说明:
-
所有API均包含同步执行(execute)和异步执行(executeAsync)两种执行方式。
-
同步执行会返回指定的业务结果类,若执行出错则会抛出UfileException为父类的异常;
-
异步执行需要传入UfileCallback
的回调接口,执行成功时会回调onResponse,泛型 为回调结果(即:同步执行的返回类型),**值得注意的是,若Ufile Server业务错误,也会回调onResponse,请注意结果类中的信息**,若出现异常,则回调onError。 -
如果是上传下载等耗时API,建议使用异步执行(executeAsync),并可以重写UfileCallback中的onProgress回调来进行进度监听
-
配置UfileClient
-
必须在使用UfileClient之前调用,即:必须是UfileClient第一个调用的方法才有效。否则使用默认UfileClient.Config
1 2 3 4 5 6
UfileClient.configure(new UfileClient.Config( new HttpClient.Config(int maxIdleConnections, long keepAliveDuration, TimeUnit keepAliveTimeUnit) .setTimeout(连接超时ms,读取超时ms,写入超时ms) .setExecutorService(线程池) .addInterceptor(okhttp3拦截器) .addNetInterceptor(okhttp3网络拦截器)));
Bucket相关操作
1
2
3
4
5
6
7
// Bucket相关API的授权器
BucketAuthorization BUCKET_AUTHORIZER = new UfileBucketLocalAuthorization(
"Your PublicKey", "Your PrivateKey");
UfileClient.bucket(BUCKET_AUTHORIZER)
.APIs // Bucket相关操作API
.execute() or executeAsync(UfileCallback<T>)
创建Bucket
-
同步
1 2 3 4 5 6 7 8 9
try { BucketResponse res = UfileClient.bucket(BUCKET_AUTHORIZER) .createBucket(bucketName, region, bucketType) .execute(); } catch (UfileClientException e) { e.printStackTrace(); } catch (UfileServerException e) { e.printStackTrace(); }
-
异步
1 2 3 4 5 6 7 8 9 10 11 12 13
UfileClient.bucket(BUCKET_AUTHORIZER) .createBucket(bucketName, region, bucketType) .executeAsync(new UfileCallback<BucketResponse>() { @Override public void onResponse(BucketResponse response) { } @Override public void onError(Request request, ApiError error, UfileErrorBean response) { } });
对象相关操作
关于 ObjectConfig 的 Region 与访问域名说明,请参考 地域和域名地址
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 对象相关API的授权器
ObjectAuthorization OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(
"Your PublicKey", "Your PrivateKey");
/**
* 您也可以创建远程对象相关API的授权器,远程授权器将签名私钥放于签名服务器上,更为安全
* 远程签名服务端示例代码在 (https://github.com/ucloud/ufile-sdk-auth-server)
* 您也可以自行继承ObjectRemoteAuthorization来重写远程签名逻辑
*/
ObjectAuthorization OBJECT_AUTHORIZER = new UfileObjectRemoteAuthorization(
您的公钥,
new ObjectRemoteAuthorization.ApiConfig(
"http://your_domain/applyAuth",
"http://your_domain/applyPrivateUrlAuth"
));
// 对象操作需要ObjectConfig来配置您的地区和域名后缀
ObjectConfig config = new ObjectConfig("your bucket region", "ufileos.com");
// 说明:此处使用的是 US3 协议访问域名(bucket.region.ufileos.com)。
// 请勿将 S3 兼容 Endpoint(例如 https://s3-{region}.ufileos.com)填入 ObjectConfig。
/**
* 您也可以使用已登记的自定义域名
* 注意:此处的 `your_domain.com` 仅为示例,自定义域名不要求包含 `www`(可按需使用根域或任意子域)。
* 该域名需解析(如 CNAME)到某个特定的 bucket + region(以及域名后缀)对应的访问域名。
* 例如:`your_domain.com` -> `your_bucket.bucket_region.ufileos.com`
*/
ObjectConfig config = new ObjectConfig("http://your_domain.com");
/**
* ObjectConfig同时支持从本地文件来导入
* 配置文件内容必须是含有以下参数的json字符串:
* {"Region":"","ProxySuffix":""}
* 或
* {"CustomDomain":""}
*/
try {
ObjectConfig.loadProfile(new File("your config profile path"));
} catch (UfileFileException e) {
e.printStackTrace();
}
UfileClient.object(OBJECT_AUTHORIZER, config)
.APIs // 对象存储相关API
.execute() or executeAsync(UfileCallback<T>)
使用 STS 临时凭证说明
版本支持:SDK v2.7.4+ 支持通过
.withSecurityToken(securityToken)传入 STSSecurityToken。
SecurityToken的使用场景:仅当您使用 STS 临时安全凭证(临时AccessKeyId+ 临时AccessKeySecret+SecurityToken三元组)访问 US3 时,才需要配置SecurityToken。- 若您使用的是账号长期 API 公私钥,则无需配置
SecurityToken(保持为空即可)。
- 若您使用的是账号长期 API 公私钥,则无需配置
- 临时
AccessKeyId/AccessKeySecret的填写位置:与长期密钥一致,仍通过授权器构造函数传入,例如new UfileObjectLocalAuthorization(AccessKeyId, AccessKeySecret)。 SecurityToken的填写方式:- 普通对象接口(Put/Get/Delete/List 等):调用链上通过
.withSecurityToken(securityToken)传入;SDK 会自动在请求头中追加SecurityToken。 - 预签名 URL(下载/上传):生成 URL 时通过
.withSecurityToken(securityToken)传入;SDK 会将SecurityToken追加到预签名 URL 的 query 参数中。客户端使用该 URL 发起 HTTP PUT/GET 时,无需额外设置SecurityToken请求头。
- 普通对象接口(Put/Get/Delete/List 等):调用链上通过
示例(对象上传:STS 临时凭证):
1
2
3
4
5
6
7
8
9
10
ObjectAuthorization STS_OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(
"Your STS AccessKeyId", "Your STS AccessKeySecret");
String securityToken = "Your SecurityToken";
UfileClient.object(STS_OBJECT_AUTHORIZER, config)
.withSecurityToken(securityToken)
.putObject(new File("your file path"), "mimeType")
.nameAs("save as keyName")
.toBucket("upload to which bucket")
.execute();
示例(生成预签名上传 URL:STS 临时凭证):
1
2
3
4
5
GenerateObjectPrivateUploadUrlApi.UploadUrlInfo urlInfo = UfileClient.object(STS_OBJECT_AUTHORIZER, config)
.getUploadUrlToPrivateBucket("keyName", "bucketName", 3600)
.withContentType("application/octet-stream")
.withSecurityToken(securityToken)
.createUrlWithHeaders();
上传文件
-
同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
File file = new File("your file path"); try { PutObjectResultBean response = UfileClient.object(Constants.OBJECT_AUTHORIZER, config) .putObject(file, "mimeType") .nameAs("save as keyName") .toBucket("upload to which bucket") /** * 是否上传校验MD5, Default = true */ // .withVerifyMd5(false) /** * 指定progress callback的间隔, Default = 每秒回调 */ // .withProgressConfig(ProgressConfig.callbackWithPercent(10)) /** * 配置进度监听 */ .setOnProgressListener(new OnProgressListener() { @Override public void onProgress(long bytesWritten, long contentLength) { } }) .execute(); } catch (UfileClientException e) { e.printStackTrace(); } catch (UfileServerException e) { e.printStackTrace(); }
-
异步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
File file = new File("your file path"); UfileClient.object(OBJECT_AUTHORIZER, config) .putObject(file, "mimeType") .nameAs("save as keyName") .toBucket("upload to which bucket") /** * 是否上传校验MD5, Default = true */ // .withVerifyMd5(false) /** *指定progress callback的间隔, Default = 每秒回调 */ // .withProgressConfig(ProgressConfig.callbackWithPercent(10)) .executeAsync(new UfileCallback<PutObjectResultBean>() { @Override public void onProgress(long bytesWritten, long contentLength) { } @Override public void onResponse(PutObjectResultBean response) { } @Override public void onError(Request request, ApiError error, UfileErrorBean response) { } });