Get file download URL
Updated at:2025-11-03
Users can obtain the URL of a specified object through the following code:
Java
1public String generatePresignedUrl(BosClient client, String bucketName, String objectKey, int expirationInSeconds) {
2 //Specify the name of the bucket where the object that the user needs to obtain is located, the name of the object, and the valid duration of the URL
3 URL url = client.generatePresignedUrl(<bucketName>, <objectKey>, <expirationInSeconds>);
4
5 return url.toString();
6}
Description:
- Before calling this function, users need to manually set the endpoint to the domain name of the corresponding region. Baidu AI Cloud currently supports multiple regions. Please refer toRegion and Endpoint.
expirationInSecondsis the specified URL validity period, calculated from the current time. It is an optional parameter, and the system default value is 1,800 seconds if not configured. To set a permanent non-expiration time, theExpirationInSecondsparameter can be set to -1. You cannot set it to any other negative value.- If the file to be obtained is expected to be publicly readable, the corresponding URL link can be quickly concatenated and obtained through simple rules:
http://$bucketName.$region.bcebos.com/$objectKeyorhttp://$region.bcebos.com/$bucketName/$objectKey
It supports getting download URLs through the STS method. For configuring STS to access BOS, see the initialization page. The code example is as follows:
Java
1public String generatePresignedUrl(String bucketName, String objectKey, int expirationInSeconds) {
2 // Get STS
3 BceCredentials credentials = new DefaultBceCredentials(BOS_AK, BOS_SK);
4 StsClient stsClient = new StsClient(
5 new BceClientConfiguration().withEndpoint("http://sts.bj.baidubce.com").withCredentials(credentials)
6 );
7 GetSessionTokenResponse response = stsClient.getSessionToken(new GetSessionTokenRequest());
8
9 // Generate bosClient
10 BceCredentials bosstsCredentials = new DefaultBceSessionCredentials(
11 response.getAccessKeyId(),
12 response.getSecretAccessKey(),
13 response.getSessionToken());
14 BosClientConfiguration config = new BosClientConfiguration();
15 config.setCredentials(bosstsCredentials);
16 config.setEndpoint(ENDPOINT);
17 BosClient bosClient = new BosClient(config);
18
19 //Specify the name of the bucket where the object that the user needs to obtain is located, the name of the object, and the valid duration of the URL
20 URL url = bosClient.generatePresignedUrl(bucketName, objectKey, expirationInSeconds);
21
22 return url.toString();
23}
