This topic describes how to use upload callback.

For the complete code used to implement upload callback, visit GitHub. For more information about upload callback, see Callback.

The following code provides an example on how to use upload callback:

// This example uses the endpoint of the China (Hangzhou) region. Specify the actual endpoint based on your requirements.
String endpoint = "";
// Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS, because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>";
// Specify the IP address of the server to which you want send the callback request, for example, or
String callbackUrl = "<yourCallbackServerUrl>";

// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

String content = "Hello OSS";
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,new ByteArrayInputStream(content.getBytes()));

// Configure upload callback parameters.
Callback callback = new Callback();
// (Optional) Configure the value of the host field carried in the callback request header. This value is the same as the value of the host field specified for your server.
// callback.setCallbackHost("yourCallbackHost");
// Configure the value of the body field carried in the callback request.
// Configure Content-Type for the callback request.
// Configure custom parameters for the callback request. Each custom parameter consists of a key and a value. The key must start with x:.
callback.addCallbackVar("x:var1", "value1");
callback.addCallbackVar("x:var2", "value2");

PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

// Read the response for the upload callback request.
byte[] buffer = new byte[1024];
// If you do not close the reader after the data is read, connection leaks may occur. Consequently, no available connections are left and an exception occurs.

// Shut down the OSSClient.

For more information about upload callback, see upload callback in Developer Guide.