OSS在上传文件完成时支持提供回调(Callback)给应用服务器。您只需要在发送给OSS的请求中携带相应的Callback参数,即可实现回调。本文介绍如何使用上传回调。
说明 由于加入了回调请求和响应的过程,相比简单上传,使用回调通知机制一般会导致客户端花费更多的等待时间。
PutObjectRequest put = new PutObjectRequest(testBucket, testObject, uploadFilePath); put.setCallbackParam(new HashMap<String, String>() { { put("callbackUrl", "192.168.10.106/callback"); put("callbackHost", "yourCallbackHost"); put("callbackBodyType", "application/json"); put("callbackBody", "{\"mimeType\":${mimeType},\"size\":${size}}"); } }); OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() { @Override public void onSuccess(PutObjectRequest request, PutObjectResult result) { Log.d("PutObject", "UploadSuccess"); // 只有设置了servercallback,该值才有数据。 String serverCallbackReturnJson = result.getServerCallbackReturnBody(); Log.d("servercallback", serverCallbackReturnJson); } @Override public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) { // 异常处理。 } });
如果需要支持自定义参数,请参考如下示例设置:
put.setCallbackParam(new HashMap<String, String>() { { put("callbackUrl", "http://192.168.192.125/leibin/notify.php"); put("callbackHost", "yourCallbackHost"); put("callbackBodyType", "application/json"); put("callbackBody", "{\"object\":${object},\"size\":${size},\"my_var1\":${x:var1},\"my_var2\":${x:var2}}"); } }); put.setCallbackVars(new HashMap<String, String>() { { put("x:var1", "value1"); put("x:var2", "value2"); } });
关于Callback的更多信息,请参见API参考中的Callback。