Last update:2025-08-18 15:54:12
This document provides a detailed guide on getting started with and using the main features of the Java SDK v2 for Object Storage Service.
Ensure that Java is installed on your system. Java 1.7 or later is recommended. You can check your Java version by running java -version.
The Java SDK Rest v2 provides various sample programs, including the following:
| Sample File | Description |
|---|---|
| DownloadSample | Basic file download |
| SimpleMultipartUploadSample | Multipart upload |
| ListObjectsSample | List objects |
| ObjectOperationsSample | Object management |
| DeleteObjectsSample | Batch object deletion |
| BucketLifecycleSample | Bucket lifecycle management |
| ConcurrentCopyPartSample | Multi-threaded multipart copy |
| ConcurrentDownloadObjectSample | Multi-threaded multipart download |
| ConcurrentUploadPartSample | Multi-threaded multipart upload |
| CreateFolderSample | Create a “folder” |
| DeleteObjectsSample | Batch object deletion |
| ListBucketsSample | List buckets |
| ListObjectsV2Sample | List objects (v2) |
| ObjectMetaSample | Set object metadata |
| PostObjectSample | Form upload |
| RestoreObjectSample | Restore (unfreeze) object |
Before performing any operations, you must install the Java SDK. You can download the SDK from GitHub.
Add as a Dependency to a Maven Project
<dependency>
<groupId>com.chinanetcenter.wcs.sdk</groupId>
<artifactId>wcs-java-sdk-v2</artifactId>
<version>1.0.3</version>
</dependency>
Importing JARs in IntelliJ IDEA
For version 1.0.0 as an example, follow these steps:
wcs-java-sdk-rest-v2-1.0.0.jar file and all JAR files from the lib directory into your project.File -> Project Structure -> Modules -> Dependencies -> + -> JARs or directories.WosClient is the Java client for managing buckets and objects. Before using the Java SDK, you must initialize WosConfiguration and adjust the default settings if necessary.
// Retrieve your Access Key (ak) and Secret Key (sk) from the Console: User Center > User Information > AccessKey Management
// Retrieve your endpoint and regionName from Console: Object Storage > Bucket Overview
String endPoint = "https://your-endpoint";
String regionName = "your regionName";
String ak = "*** Provide your Access Key ***";
String sk = "*** Provide your Secret Key ***";
WosConfiguration config = new WosConfiguration();
config.setSocketTimeout(30000);
config.setConnectionTimeout(10000);
config.setEndPoint(endPoint);
config.setRegionName(regionName);
// Create WosClient instance
WosClient wosClient = new WosClient(ak, sk, config);
// Close the wosClient
wosClient.close();
// Create WosClient instance
WosClient wosClient = new WosClient(ak, sk, config, regionName);
// Close the wosClient
wosClient.close();
Note: When creating a new WosClient, you must specify the Endpoint. You can have one or more WosClient instances in your project. WosClient is thread-safe and supports concurrent usage.
You can configure WosClient using WosConfiguration, which supports parameters such as timeouts, maximum connections, and more. Details are as follows:
| Configuration | Description | Method |
|---|---|---|
| connectionTimeout | Set HTTP/HTTPS connection timeout (milliseconds). Default: 60000. | WosConfiguration.setConnectionTimeout |
| socketTimeout | Set socket timeout (milliseconds). Default: 60000. | WosConfiguration.setSocketTimeout |
| idleConnectionTime | Time to close idle connections. Connections are closed if idle time exceeds this value (milliseconds). Default: 30000. | WosConfiguration.setIdleConnectionTime |
| maxIdleConnections | Maximum idle connections in the connection pool. Default: 1000. | WosConfiguration.setMaxIdleConnections |
| maxConnections | Maximum allowed concurrent HTTP requests. Default: 1000. | WosConfiguration.setMaxConnections |
| maxErrorRetry | Number of retry attempts on failure. Default: 3. | WosConfiguration.setMaxErrorRetry |
| endPoint | Object storage service address (protocol, domain, port), e.g., “https://your-endpoint:443” | WosConfiguration.setEndPoint |
| readBufferSize | Socket stream read buffer (bytes). Default: -1 (disabled). | WosConfiguration.setReadBufferSize |
| writeBufferSize | Socket stream write buffer (bytes). Default: -1 (disabled). | WosConfiguration.setWriteBufferSize |
| pathStyle | If false, use bucketName.endpoint domain format; otherwise, use ‘endpoint/bucketName’ format. |
WosConfiguration.setPathStyle |
The Java SDK supports common operations including:
The code below demonstrates how to upload an object:
wosClient.putObject("bucketname", "objectname", new ByteArrayInputStream("Hello WOS".getBytes()));
The following code shows how to retrieve the content of an object:
WosObject wosObject = wosClient.getObject("bucketname", "objectname");
InputStream content = wosObject.getObjectContent();
if (content != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
while (true) {
String line = reader.readLine();
if (line == null)
break;
System.out.println("\n" + line);
}
reader.close();
}
Notes:
wosObject.getObject returns a WosObject instance containing both content and metadata.wosObject.getObjectContent to get an InputStream for reading the object; please close the stream when finished.After a series of object uploads, you might need to list the contents of a bucket. Example:
ObjectListing objectListing = wosClient.listObjects("bucketname");
for (WosObject wosObject : objectListing.getObjects()) {
System.out.println(" - " + wosObject.getObjectKey() + " " + "(size = " + wosObject.getMetadata().getContentLength() + ")");
}
Notes:
wosClient.listObjects returns an ObjectListing instance, through which you can access object details via ObjectListing.getObjects.The following code shows how to delete a specific object:
wosClient.deleteObject("bucketname", "objectname");
The following example demonstrates how to generate a signed URL for accessing an object:
TemporarySignatureRequest req = new TemporarySignatureRequest(HttpMethodEnum.GET, 300);
req.setBucketName(bucketName);
req.setObjectKey(objectKey);
TemporarySignatureResponse res = wosClient.createTemporarySignature(req);
System.out.println("Getting object using temporary signature URL:");
System.out.println("\t" + res.getSignedUrl());
After calling an API via the WOS client, if no exception is thrown, the return value is valid—either a base SDK response class or a subclass instance. If an exception occurs, retrieve error information from the SDK’s custom exception object.
The following code demonstrates the general usage pattern with the WOS client:
// You may maintain a single global WosClient instance in your project.
// WosClient is thread-safe and supports concurrent use.
WosClient wosClient = null;
try {
String endPoint = "https://your-endpoint";
String regionName = "your regionName";
String ak = "*** Provide your Access Key ***";
String sk = "*** Provide your Secret Key ***";
// Create config
WosConfiguration config = new WosConfiguration();
config.setSocketTimeout(30000);
config.setConnectionTimeout(10000);
config.setEndPoint(endPoint);
config.setRegionName(regionName);
// Create WosClient instance
wosClient = new WosClient(ak, sk, config);
// Call API—for example, upload an object
HeaderResponse response = wosClient.putObject("bucketname", "objectname", new File("localfile")); // 'localfile' is the path to the file to be uploaded; provide the full filename
System.out.println(response);
} catch (WosException e) {
System.out.println("HTTP Code: " + e.getResponseCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Error Message: " + e.getErrorMessage());
System.out.println("Request ID: " + e.getErrorRequestId());
System.out.println("Host ID: " + e.getErrorHostId());
} finally {
// Close the WosClient instance; if you have a global WosClient, you do not need to close after every API call
// Do not use the WosClient again after calling wosClient.close()
if (wosClient != null) {
try {
// wosClient.close();
} catch (IOException e) {
// Handle exception if needed
}
}
}