Last active
February 2, 2018 07:18
-
-
Save 410063005/d0e75c5e5bfe21ea62e11ba3db129c52 to your computer and use it in GitHub Desktop.
CosClient 上传腾讯云对象存储服务
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"app_id":"your app_id", | |
"region":"ap-guangzhou", | |
"sign_duration":600, | |
"bucket":"your bucket name", | |
"secret_id":"your secret id", | |
"secret_key":"your secret key" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 上传腾讯云cos. | |
* <p> | |
* Created by 410063005 on 2018/1/31. | |
*/ | |
// Config: https://cloud.tencent.com/document/product/436/12159 | |
// Usage: | |
// File file = new File(Environment.getExternalStorageDirectory(), "hello.png"); | |
// CosClient.create(IndexActivity.this, getAssets().open("heap.json")).upload(file); | |
public class CosClient { | |
private static final String TAG = "CosClient"; | |
private static final boolean DEBUG = true; | |
private CosXmlService cosXmlService; | |
private CosClientParams cosClientParams; | |
public static CosClient createDefault(Context context) { | |
return new CosClient(context, CosClientParams.create()); | |
} | |
public static CosClient create(Context context, File config) throws IOException { | |
return new CosClient(context, CosClientParams.create(config)); | |
} | |
public static CosClient create(Context context, InputStream is) throws IOException { | |
return new CosClient(context, CosClientParams.create(is)); | |
} | |
private CosClient(Context context, CosClientParams params) { | |
cosClientParams = params; | |
cosXmlService = createCosXmlService(context.getApplicationContext()); | |
} | |
public void upload(File file) { | |
upload(file, null, null); | |
} | |
public void upload(File file, @Nullable String cosName, @Nullable final UploadCallback callback) { | |
if (cosName == null || cosName.isEmpty()) { | |
cosName = UUID.randomUUID().toString(); | |
} | |
String srcPath = file.getAbsolutePath(); | |
PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientParams.bucket, cosName, srcPath); | |
putObjectRequest.setSign(cosClientParams.signDuration, null, null); | |
MyCosXmlResultListener cosXmlResultListener = new MyCosXmlResultListener(callback); | |
putObjectRequest.setProgressListener(cosXmlResultListener); | |
cosXmlService.putObjectAsync(putObjectRequest, cosXmlResultListener); | |
} | |
private CosXmlService createCosXmlService(Context context) { | |
//创建 CosXmlServiceConfig 对象,根据需要修改默认的配置参数 | |
CosXmlServiceConfig cosXmlServiceConfig = new CosXmlServiceConfig.Builder() | |
.isHttps(true) | |
.setAppidAndRegion(cosClientParams.appId, cosClientParams.region) | |
.setDebuggable(true) | |
.builder(); | |
/* | |
* | |
* 创建 ShortTimeCredentialProvider 签名获取类对象,用于使用对象存储服务时计算签名. | |
* 参考 SDK 提供签名格式,可实现自己的签名方法(extends BasicLifecycleCredentialProvider 以及实现 * * fetchNewCredentials() 方法). | |
* 此处使用SDK提供的默认签名计算方法. | |
* | |
*/ | |
ShortTimeCredentialProvider localCredentialProvider = new ShortTimeCredentialProvider( | |
cosClientParams.secretId, | |
cosClientParams.secretKey, | |
cosClientParams.signDuration); | |
//创建 CosXmlService 对象,实现对象存储服务各项操作. | |
return new CosXmlService(context, cosXmlServiceConfig, localCredentialProvider); | |
} | |
private static void debug(String message) { | |
if (DEBUG) { | |
Log.i(TAG, message); | |
} | |
} | |
private static class CosClientParams { | |
private static final String APP_ID = "your app_id"; | |
private static final String REGION = "ap-guangzhou"; //"gz"; | |
// secretKey 的有效时间,单位秒 | |
private static final long SIGN_DURATION = 600; | |
private static final String BUCKET = "your bucket name"; | |
private static final String SECRET_ID = "your secret id"; | |
private static final String SECRET_KEY = "your secret key"; | |
String appId; | |
String region; | |
long signDuration; | |
String bucket; | |
String secretId; | |
String secretKey; | |
public static CosClientParams create() { | |
CosClientParams params = new CosClientParams(); | |
params.appId = APP_ID; | |
params.region = REGION; | |
params.signDuration = SIGN_DURATION; | |
params.bucket = BUCKET; | |
params.secretId = SECRET_ID; | |
params.secretKey = SECRET_KEY; | |
return params; | |
} | |
public static CosClientParams create(InputStream is) throws IOException { | |
BufferedReader reader = new BufferedReader(new InputStreamReader(is)); | |
StringBuilder config = new StringBuilder(); | |
String line; | |
while ((line = reader.readLine()) != null) { | |
config.append(line); | |
} | |
try { | |
JSONObject json = new JSONObject(config.toString()); | |
CosClientParams params = new CosClientParams(); | |
params.appId = json.getString("app_id"); | |
params.region = json.getString("region"); | |
params.signDuration = json.getLong("sign_duration"); | |
params.bucket = json.getString("bucket"); | |
params.secretId = json.getString("secret_id"); | |
params.secretKey = json.getString("secret_key"); | |
return params; | |
} catch (JSONException e) { | |
throw new IOException(e); | |
} | |
} | |
public static CosClientParams create(File file) throws IOException { | |
InputStream bis = new FileInputStream(file); | |
try { | |
return create(bis); | |
} finally { | |
try { | |
bis.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
private static class MyCosXmlResultListener implements CosXmlResultListener, CosXmlProgressListener { | |
private UploadCallback callback; | |
MyCosXmlResultListener(UploadCallback uploadCallback) { | |
this.callback = uploadCallback; | |
} | |
@Override | |
public void onSuccess(CosXmlRequest cosXmlRequest, CosXmlResult cosXmlResult) { | |
debug("success: " + cosXmlResult.accessUrl); | |
if (callback != null) { | |
callback.onSuccess(cosXmlResult.httpCode, cosXmlResult.httpMessage, cosXmlResult.accessUrl); | |
} | |
} | |
@Override | |
public void onFail(CosXmlRequest cosXmlRequest, CosXmlClientException clientException, | |
CosXmlServiceException serviceException) { | |
String errorMsg = clientException != null ? clientException.toString() : serviceException.toString(); | |
debug(errorMsg); | |
if (callback != null) { | |
callback.onFail(errorMsg); | |
} | |
} | |
@Override | |
public void onProgress(long progress, long max) { | |
float result = (float) (progress * 100.0 / max); | |
debug("progress =" + (long) result + "%"); | |
if (callback != null) { | |
callback.onProgress(progress, max); | |
} | |
} | |
} | |
public interface UploadCallback { | |
void onProgress(long progress, long max); | |
void onSuccess(int httpCode, String httpMessage, String accessUrl); | |
void onFail(String errorMessage); | |
} | |
public static class UploadCallbackAdapter implements UploadCallback { | |
public void onFinish() { | |
} | |
@Override | |
public void onProgress(long progress, long max) { | |
} | |
@Override | |
public void onSuccess(int httpCode, String httpMessage, String accessUrl) { | |
onFinish(); | |
} | |
@Override | |
public void onFail(String errorMessage) { | |
onFinish(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment