Java SDK FAQs

Last updated: 2026-04-28 16:46:53

What do I do if the client network is normal, while the access to COS over HTTP is very slow, or the error message “Connection reset” is reported?

In some regions, carriers may hijack COS endpoints. Therefore, you are advised to access COS over HTTPS.

What do I do if java.lang.NoSuchMethodError is reported when I run the SDK?

Cause: This issue generally occurs due to JAR package conflicts. For example, the httpclient library in the user's project does not have method A, but the SDK's dependent JAR package uses method A. Due to the runtime loading order, the user's project httpclient library is loaded, resulting in a NoSuchMethodError exception at runtime. Solutions: 1. Change the version of the package causing the NoSuchMethodError in your project to match the corresponding library version in the SDK's pom.xml. 2. Replace cos-java-sdk with cos_api-bundle. This approach installs all dependencies of cos-java-sdk independently, occupying more space.
<groupId>com.qcloud</groupId>
<artifactId>cos_api-bundle</artifactId>
<version>5.6.35</version>

What is the default timeout duration of the Java SDK?

Both the default connection and read/write timeout periods of the Java SDK are 30,000 ms. You can use the SetConnectionTimeoutMs and setSocketTimeout methods in the SDK to adjust them.

What do I do if the upload with the Java SDK is slow and IOException is frequently printed in the log?

Troubleshoot the problem as follows:
1. Check whether you are accessing COS through a public network. Currently, CVM instances that are in the same region as COS can access COS through a private network (the IP ranges resolved by the private endpoint are 10, 100, and 169). For more information about COS endpoints, please see Regions and Access Endpoints. If a public network is used, check whether the egress bandwidth is too small or whether bandwidth resources are occupied by other programs.
2. Ensure that the logs in the production environment are not set to DEBUG level. The INFO level is recommended.
3. Currently, the simple upload speed is up to 10 MB/s, and the speed of 32 concurrent uploads using advanced APIs can reach 60 MB/s. If the speed is far lower than these two values, see steps 1 and 2.
4. If IOException is printed in the WARN level logs, it can be ignored, and the SDK will retry. IOException may be caused by a slow network connection. For the solutions, see steps 1 and 2.

What do I do if there is a plus sign (+) in the requested upload path, throwing "403 SignatureDoesNotMatch"?

Possible cause: The urlencode encoding error may be caused by the user's Java environment httpclient version. Suggested solution: You can resolve this issue by using the following method: 1. Use httpclient version 4.5.3.
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
Solution 2: Replace cos-java-sdk with cos_api-bundle. In this case, all dependencies of cos-java-sdk are installed independently and thus more space will be used.
<groupId>com.qcloud</groupId>
<artifactId>cos_api-bundle</artifactId>
<version>5.6.35</version>

What should I do if the Java SDK reports an error indicating that a certain dependency version is too low?

Cause: The dependency version in the user's Java environment conflicts with the required dependency version of the Java SDK. Solutions: 1. Upgrade the corresponding dependency to the required version as prompted. 2. Replace cos-java-sdk with cos_api-bundle. This approach installs all dependencies of cos-java-sdk independently, occupying more space.
<groupId>com.qcloud</groupId>
<artifactId>cos_api-bundle</artifactId>
<version>5.6.35</version>

How do I create a directory in the SDK?

In COS, both files and directories are objects, where directories are objects that end with /. When creating a file, you don't need to create a directory. For example, when you create a file with the object key of xxx/yyy/zzz.txt, set the key to xxx/yyy/zzz.txt instead of creating the object xxx/yyy/. Directories are separated by / to show the hierarchy when displayed in the console. To create a directory object, use the following sample code:
String bucketName = "examplebucket-1250000000";
String key = "folder/images/";
// A directory object is an empty file that ends with /, where a byte stream with a length of 0 is uploaded
InputStream input = new ByteArrayInputStream(new byte[0]);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(0);

PutObjectRequest putObjectRequest =
new PutObjectRequest(bucketName, key, input, objectMetadata);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

How do I use HTTPS in the SDK?

In the SDK, relevant configuration items are put in the ClientConfig class. Below is the sample code:
// Initialize user authentication information (secretId and secretKey).
String secretId = "COS_SECRETID";
String secretKey = "COS_SECRETKEY";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// Set the bucket region. For abbreviations of COS regions, see https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing-1"));
// Configure HTTPS.
clientConfig.setHttpProtocol(HttpProtocol.https);
// Generate a COS client.
COSClient cosClient = new COSClient(cred, clientConfig);

How do I use a proxy in the SDK?

If you need to use a proxy to access COS, you can configure a proxy IP (or an endpoint) and port in the ClientConfig class. Below is the sample code:
// Initialize user authentication information (secretId and secretKey).
String secretId = "COS_SECRETID";
String secretKey = "COS_SECRETKEY";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// Set the bucket region. For abbreviations of COS regions, see https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing-1"));
// Configure a proxy (both the IP and port need to be set).
// Set the proxy IP (or pass an endpoint).
clientConfig.setHttpProxyIp("192.168.2.3");
// Set the proxy port.
clientConfig.setHttpProxyPort(8080);
// Generate a COS client.
COSClient cosClient = new COSClient(cred, clientConfig);

How do I set up custom EndpointBuilder?

In scenarios where the endpoint needs to be specified for an API request, you need to implement the buildGeneralApiEndpoint and buildGetServiceApiEndpoint functions in the EndpointBuilder API to specify the remote endpoints for a general API request and GETService request, respectively. Below is the sample code:
// Step 1. Implement the two functions in the EndpointBuilder API.
class SelfDefinedEndpointBuilder implements EndpointBuilder {
@Override
public String buildGeneralApiEndpoint(String bucketName) {
return String.format("%s.%s", bucketName, "mytest.com");
}

@Override
public String buildGetServiceApiEndpoint() {
return "service.mytest.com";
}
}

// Step 2. Initialize the client.
String secretId = "COS_SECRETID";
String secretKey = "COS_SECRETKEY";
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
SelfDefinedEndpointBuilder selfDefinedEndpointBuilder = new SelfDefinedEndpointBuilder();
ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));
clientConfig .setEndpointBuilder(selfDefinedEndpointBuilder);
COSClient cosClient = new COSClient(cred, clientConfig);

Do I need to add the / prefix to key values used in SDK operations such as upload, download, and batch delete?

The key value for object storage does not require a prefix like /. For example, if you set the object key value to "exampleobject" when uploading, you can access it via the URL: http://cos.ap-guangzhou.myqcloud.com/exampleobject.
Note
Do not pass in a key prefixed with / in a batch delete request. Otherwise, the object deletion may fail.
COS Java SDK of an earlier version supports only App IDs starting with, for example, 125. If you are using an App ID starting with 130, it is recommended that you update the SDK to the latest version. For more information on how to download and install the Java SDK, see Java SDK documentation.

What do I do if the COS Java SDK reports an error when I upload large files?

To upload files larger than 5 GB by using the Java SDK, we recommend you use the advanced upload API. It automatically determines whether to use simple or multipart upload based on the length and data type of your file.

How do I obtain the file upload progress in the Java SDK?

To obtain the upload progress, it is recommended to use the advanced upload interface. By invoking the getProgress() method of the Upload class, you can acquire the progress through the TransferProgress class.

Does Java SDK support calculating the CRC64 checksum of a local file?

No. You need to implement this feature on the business side. For more information, please see Java issues.

How is the 21-bit CRC64 checksum returned by COS compared with the locally calculated CRC64 checksum?

The long of Java supports only 20 bits. Therefore, you can compare as follows:
CRC64 localCRC = new CRC64();
// Calculate the local CRC64.
localCRC.update();
//...

// Convert the CRC64 returned by COS to long:
cosCRC = crc64ToLong(strCOSCRC);

// Perform comparison.
if (cosCRC == localCRC.getValue()) {
xxx
}

// Convert the COS-returned CRC64 into a long in Java.
long crc64ToLong(String crc64) {
if (crc64.charAt(0) == '-') {
return negativeCrc64ToLong(crc64);
} else {
return positiveCrc64ToLong(crc64);
}
}

long positiveCrc64ToLong(String strCrc64) {
BigInteger crc64 = new BigInteger(strCrc64);
BigInteger maxLong = new BigInteger(Long.toString(Long.MAX_VALUE));

int maxCnt = 0;

while (crc64.compareTo(maxLong) > 0) {
crc64 = crc64.subtract(maxLong);
maxCnt++;
}

return crc64.longValue() + Long.MAX_VALUE * maxCnt;
}

long negativeCrc64ToLong(String strCrc64) {
BigInteger crc64 = new BigInteger(strCrc64);
BigInteger minLong = new BigInteger(Long.toString(Long.MIN_VALUE));

int minCnt = 0;

while (crc64.compareTo(minLong) < 0) {
crc64 = crc64.subtract(minLong);
minCnt++;
}

return crc64.longValue() + Long.MIN_VALUE * minCnt;
}

Can Java SDK use persistent connections?

The Java SDK uses persistent connections by default.

How to use the Java SDK to get all the paths to the specified directory and determine whether the paths are files or folders?

You can use the List Objects feature in the Java SDK to list objects within a bucket. Specify a directory prefix using the prefix parameter.

What should I do if the Java SDK reports the error "java.lang.IllegalStateException: Connection pool shut down"?

1. COSClient is a thread-safe class that allows multiple threads to access a single instance. Internally, it maintains a connection pool, and creating multiple instances may lead to resource exhaustion. Ensure that there is only one instance throughout the program's lifecycle and call the COSClient.shutdown() method to close it when it is no longer needed. If you need to create a new instance, close the previous one first. It is recommended to use only one COSClient per process and call COSClient.shutdown() when the program is completely finished and exits.
2. In the advanced interface wrapper class TransferManager, COSClient is also used. It is recommended to call TransferManager.shutdownNow(false) when the program is completely finished and exits. Additionally, if you reuse another COSClient when creating a TransferManager instance, add the parameter false when closing (i.e., TransferManager.shutdownNow(false)) to avoid closing the reused COSClient and causing errors in other places where COSClient is used.

What should I do if the Java SDK reports the error "com.qcloud.cos.exception.CosServiceException: Request has expired (Status Code: 403; Error Code: AccessDenied)"?

This issue is caused by an expired signature. Regenerating the signature should resolve the problem. If the same error persists after regenerating the signature, check if the local time on the machine is set to standard Beijing time.