This topic describes how to use temporary access credentials provided by Security Token Service (STS) or a signed URL to temporarily access Object Storage Service (OSS) resources.

Note A validity period must be specified for temporary access credentials and a signed URL. When you use temporary access credentials to generate a signed URL that is used to perform operations such as object upload and download, the minimum validity period takes precedence. For example, you can set the validity period of your temporary access credentials to 1,200 seconds and the validity period of the signed URL generated by using the credentials to 3,600 seconds. In this case, the signed URL cannot be used to upload objects after the STS temporary access credentials expire, even if the signed URL is within its validity period.

Use STS for temporary access authorization

You can use Alibaba Cloud STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for users. You can use STS to grant a set of temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user managed by you. For more information about STS, see What is STS?

STS provides the following benefits:

  • You need only to generate an access token and send the access token to a third-party application. You do not need to expose your AccessKey pair to the third-party application. You can specify the access permissions and validity period of this token.
  • The token automatically expires after the validity period. Therefore, you do not need to manually revoke the access permissions of a token.
Notice For more information about how to configure STS, see Use a temporary credential provided by STS to access OSS. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain temporary access credentials from STS. For more information, see STS SDK overview. The temporary access credentials consist of a temporary AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. The minimum validity period of temporary access credentials is 900 seconds. The maximum validity period of temporary access credentials is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.

The following code provides an example on how to generate a signed request by using STS credentials:

import com.aliyun.oss.*;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the temporary AccessKey pair obtained from STS. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the security token obtained from STS. 
        String securityToken = "yourSecurityToken";
        // Specify the name of the bucket. Example: examplebucket. 
        //String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
        //String objectName = "exampleobject.txt";
        //String pathName = "D:\\localpath\\examplefile.txt";

        // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);

        try {
            // Perform operations on OSS resources, such as uploading or downloading objects. 
            // Upload an object. In this example, a local file is uploaded to OSS. 
            // Specify the full path of the local file. By default, if you do not specify the full path of the local file, the file is uploaded from the path of the project to which the sample program belongs. 
            //PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(pathName));
            //ossClient.putObject(putObjectRequest);

            // Download an object to your local device. If a local file has the same name as the downloaded object, the local file is overwritten by the downloaded object. Otherwise, a file is created. 
            // If the path for the downloaded object is not specified, the downloaded object is saved to the path of the project to which the sample program belongs. 
            //ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Generate a signed URL for temporary access authorization

This section provides examples on how to generate a signed URL to authorize temporary access to OSS.

Note To generate a signed URL for access over HTTPS, set the protocol in the endpoint to HTTPS.
  • Generate a signed URL

    You can generate a signed URL and provide the URL to a visitor for temporary access. When you generate a signed URL, you can specify the validity period of the URL to limit the period of time during which the visitor can access OSS.

    Notice If you use the following code to generate a signed URL that contains the plus sign (+), you may fail to access OSS by using the URL. In this case, you must replace the plus sign (+) in the URL with %2B.
  • Generate a signed URL that allows HTTP GET requests

    You can generate one or multiple signed URLs that allow HTTP GET requests at a time based on your requirements.

    • Generate a signed URL that allows HTTP GET requests

      The following code provides an example on how to generate a signed URL that allows HTTP GET requests:

      import com.aliyun.oss.*;
      import java.net.URL;
      import java.util.Date;
      
      public class Demo {
          public static void main(String[] args) throws Throwable {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              String objectName = "exampleobject.txt";
      
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
              try {
                  // Specify the validity period of the signed URL. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                  // Generate the signed URL that allows HTTP GET requests. Visitors can enter the URL in a browser to access specified OSS resources. 
                  URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
                  System.out.println(url);
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }                   
    • Generate multiple signed URLs that allow HTTP GET requests

      The following code provides an example on how to generate multiple signed URLs that allow HTTP GET requests at a time:

      import com.aliyun.oss.*;
      import java.net.URL;
      import java.util.ArrayList;
      import java.util.Date;
      import java.util.List;
      
      public class Demo {
          public static void main(String[] args) throws Throwable {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              // Specify the full paths of the objects to obtain the signed URLs of these objects at a time. 
              String objectNameList [] = {"exampleobject.txt","exampleimage.jpg"};
      
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
              try {
                  // Specify the validity period of the signed URLs. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      
                  List<URL> urlList = new ArrayList<URL>();
                  for(int i=0; i<objectNameList.length; i++){
                      URL url = ossClient.generatePresignedUrl(bucketName, objectNameList[i], expiration);
                      urlList.add(url);
                  }
                  // Display the signed URLs. 
                  for(URL url:urlList){
                      System.out.println(url);
                  }
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }
  • Generate a signed URL that allows requests using other HTTP methods

    To authorize other users to temporarily perform operations such as object upload and deletion, you must generate a signed URL that allows requests using specific HTTP methods. For example, you can generate a signed URL that allows HTTP PUT requests to authorize users to upload objects. You can generate one or multiple signed URLs that allow requests using other HTTP methods at a time based on your requirements.

    • Generate a signed URL that allows requests using other HTTP methods

      The following code provides an example on how to generate a signed URL that allows requests using other HTTP methods:

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.utils.HttpHeaders;
      import com.aliyun.oss.model.GeneratePresignedUrlRequest;
      import java.io.ByteArrayInputStream;
      import java.net.URL;
      import java.util.*;
      
      import static com.aliyun.oss.internal.OSSHeaders.OSS_USER_METADATA_PREFIX;
      
      public class Demo {
          public static void main(String[] args) throws Throwable {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              String objectName = "exampleobject.txt";
      
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
              try {
                  GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
                  // Specify the validity period of the signed URL. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                  request.setExpiration(expiration);
                  // Specify ContentType. 
                  request.setContentType("text/plain");
                  // Specify custom user metadata. 
                  request.addUserMetadata("author", "aliy");
      
                  // Generate the signed URL. 
                  URL signedUrl = ossClient.generatePresignedUrl(request);
                  System.out.println(signedUrl);
      
                  Map<String, String> requestHeaders = new HashMap<String, String>();
                  // Specify ContentType. Make sure that the value of ContentType is the same as the content type that is specified when you generate the signed URL. 
                  requestHeaders.put(HttpHeaders.CONTENT_TYPE, "text/plain");
                  // Specify custom user metadata. 
                  requestHeaders.put(OSS_USER_METADATA_PREFIX + "author", "aliy");
      
                  // Use the signed URL to upload the object. 
                  ossClient.putObject(signedUrl, new ByteArrayInputStream("Hello OSS".getBytes()), -1, requestHeaders, true);
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }      
    • Generate multiple signed URLs that allow requests using other HTTP methods

      The following code provides an example on how to generate multiple signed URLs that allow requests using other HTTP methods at a time:

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.utils.HttpHeaders;
      import com.aliyun.oss.model.GeneratePresignedUrlRequest;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.FileNotFoundException;
      import java.net.URL;
      import java.util.*;
      import static com.aliyun.oss.internal.OSSConstants.DEFAULT_OBJECT_CONTENT_TYPE;
      import static com.aliyun.oss.internal.OSSHeaders.OSS_USER_METADATA_PREFIX;
      
      public class Demo {
          public static void main(String[] args) throws Throwable {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              // Specify the full paths of the objects to obtain the signed URLs of these objects at a time. 
              String objectNameList [] = {"exampleobject.txt","exampleimage.jpg"};
              String upLoadNameArray [] = {"D:\\localpath\\examplefile1.txt","D:\\localpath\\examplefile2.jpg"};
      
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
              try {
                  // Specify the validity period of the signed URLs. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                  for(int i=0; i<objectNameList.length; i++){
                      GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectNameList[i], HttpMethod.PUT);
                      request.setExpiration(expiration);
                      // Specify ContentType. 
                      request.setContentType(DEFAULT_OBJECT_CONTENT_TYPE);
                      // Specify custom user metadata. 
                      request.addUserMetadata("author", "aliy");
      
                      // Generate the signed URLs. 
                      URL signedUrl = ossClient.generatePresignedUrl(request);
                      // Display the signed URLs. 
                      System.out.println(signedUrl);
      
                      Map<String, String> requestHeaders = new HashMap<String, String>();
                      requestHeaders.put(HttpHeaders.CONTENT_TYPE, DEFAULT_OBJECT_CONTENT_TYPE);
                      requestHeaders.put(OSS_USER_METADATA_PREFIX + "author", "aliy");
      
                      // If you want to upload a string, use the following method: 
                      //ossClient.putObject(signedUrl, new ByteArrayInputStream("Hello OSS".getBytes()), -1, requestHeaders, true);
      
                      // Use the signed URLs to upload the objects. 
                      try {
                          ossClient.putObject(signedUrl, new FileInputStream(new File(upLoadNameArray[i])), -1, requestHeaders, true);
                      } catch (FileNotFoundException e) {
                          e.printStackTrace();
                      }
                  }
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }

    Visitors can set HttpMethod to PUT and use the signed URLs to upload objects.

  • Generate one or multiple signed URLs that contain specified parameters

    You can generate a signed URL or multiple signed URLs that contain specified parameters at a time.

    • Generate a signed URL that contains specified parameters

      The following code provides an example on how to generate a signed URL that contains specified parameters:

      import com.aliyun.oss.*;
      import com.aliyun.oss.model.GeneratePresignedUrlRequest;
      import java.net.URL;
      import java.util.*;
      
      public class Demo {
          public static void main(String[] args) throws Throwable {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              String objectName = "exampleobject.txt";
      
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
              try {
                  // Create a request. 
                  GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
                  // Set HttpMethod to PUT. 
                  generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
                  // Specify custom user metadata. 
                  generatePresignedUrlRequest.addUserMetadata("author", "baymax");
                  // Specify ContentType. 
                  generatePresignedUrlRequest.setContentType("application/txt");
                  // Specify the validity period of the signed URLs. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                  generatePresignedUrlRequest.setExpiration(expiration);
                  // Generate the signed URL. 
                  URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
                  System.out.println(url);
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }
    • Generate multiple signed URLs that contain specified parameters

      The following code provides an example on how to generate multiple signed URLs that contain specified parameters:

      import com.aliyun.oss.*;
      import com.aliyun.oss.model.GeneratePresignedUrlRequest;
      import java.net.URL;
      import java.util.*;
      
      public class Demo {
          public static void main(String[] args) throws Throwable {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              // Specify the full paths of the objects to obtain the signed URLs of these objects at a time. 
              String objectNameList [] = {"exampleobject.txt","exampleimage.jpg"};
      
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
              try {
                  // Specify the validity period of the signed URLs. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                  for(int i=0; i<objectNameList.length; i++){
                      // Create a request. 
                      GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectNameList[i]);
                      // Set HttpMethod to PUT. 
                      generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
                      // Specify custom user metadata. 
                      generatePresignedUrlRequest.addUserMetadata("author", "baymax");
                      // Specify ContentType. 
                      generatePresignedUrlRequest.setContentType("application/txt");
                      generatePresignedUrlRequest.setExpiration(expiration);
                      // Generate the signed URLs. 
                      URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
                      // Display the signed URLs. 
                      System.out.println(url);
                  }
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }
  • Use a signed URL to upload or download an object
    • Use a signed URL to upload an object

      The following code provides an example on how to use a signed URL to upload an object:

      import com.aliyun.oss.*;
      import com.aliyun.oss.common.utils.DateUtil;
      import com.aliyun.oss.model.GeneratePresignedUrlRequest;
      import com.aliyun.oss.model.PutObjectResult;
      import java.io.File;
      import java.io.FileInputStream;
      import java.net.URL;
      import java.util.*;
      
      public class Demo {
          public static void main(String[] args) throws Throwable {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              String objectName = "exampleobject.txt";
              // Specify the full path of the local file. By default, if you do not specify the full path of the local file, the file is uploaded from the path of the project to which the sample program belongs. 
              String pathName = "D:\\localpath\\examplefile.txt";
      
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
      
              try {            
                  // Specify the validity period of the signed URL. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      
                  // Generate the signed URL. 
                  GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
                  // Specify the expiration time of the signed URL. 
                  request.setExpiration(expiration);
                  // Specify ContentType. 
                  request.setContentType("application/txt");
                  // Specify custom user metadata. 
                  request.addUserMetadata("author", "aliy");
                  // Generate a signed URL that allows HTTP PUT requests. 
                  URL signedUrl = ossClient.generatePresignedUrl(request);
                  System.out.println("signed url for putObject: " + signedUrl);
      
                  // Use the signed URL to send a request. 
                  File f = new File(pathName);
                  FileInputStream fin = null;
                  fin = new FileInputStream(f);
      
                  // Add headers to the PutObject request. 
                  Map<String, String> customHeaders = new HashMap<String, String>();
                  customHeaders.put("Content-Type", "application/txt");
                  customHeaders.put("x-oss-meta-author", "aliy");
      
                  PutObjectResult result = ossClient.putObject(signedUrl, fin, f.length(), customHeaders);
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }                          
    • Use a signed URL to download an object

      The following code provides an example on how to use a signed URL to download an object:

      import com.aliyun.oss.*;
      import com.aliyun.oss.model.GeneratePresignedUrlRequest;
      import com.aliyun.oss.model.OSSObject;
      import java.net.URL;
      import java.util.Date;
      import java.util.HashMap;
      import java.util.Map;
      
      public class Demo {
      
          public static void main(String[] args) throws Exception {
              // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
              String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
              // Specify the temporary AccessKey pair obtained from STS. 
              String accessKeyId = "yourAccessKeyId";
              String accessKeySecret = "yourAccessKeySecret";
              // Specify the security token obtained from STS. 
              String securityToken = "yourSecurityToken";
              // Specify the name of the bucket. Example: examplebucket. 
              String bucketName = "examplebucket";
              // Specify the full path of the object. Example: exampleobject.txt. The path cannot contain the bucket name. 
              String objectName = "exampleobject.txt";        
      
              // Create an OSSClient instance. 
              OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
              // If you use STS, use the following code to initialize the instance. 
              // After you obtain the temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
              // OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
              try {
                  // Specify the validity period of the signed URL. Unit: milliseconds. 
                  Date expiration = new Date(new Date().getTime() + 3600 * 1000);
      
                  // Generate the signed URL. 
                  GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
                  // Specify the expiration time of the signed URL. 
                  request.setExpiration(expiration);
                  Map<String, String> headers = new HashMap<String, String>();
                  // To automatically download the object when the object is accessed by using a browser and specify the name of the downloaded object, set the Content-Disposition header in the configuration file to attachment. 
                  headers.put("content-disposition","attachment");
                  // To preview the object when you use the signed URL to access the object in a browser, set the Content-Disposition header to inline and use the custom domain name that is mapped to the bucket to access the object. 
                  // headers.put("content-disposition","inline");
                  request.setHeaders(headers);
                  // Generate the signed URL that allows HTTP GET requests. 
                  URL signedUrl = ossClient.generatePresignedUrl(request);
                  System.out.println("signed url for getObject: " + signedUrl);
      
                  Map<String, String> customHeaders = new HashMap<String, String>();
                  // Add headers to a GetObject request. 
                  customHeaders.put("Range", "bytes=100-1000");
                  // Use the signed URL to send a request. 
                  OSSObject object = ossClient.getObject(signedUrl, customHeaders);
              } catch (OSSException oe) {
                  System.out.println("Caught an OSSException, which means your request made it to OSS, "
                          + "but was rejected with an error response for some reason.");
                  System.out.println("Error Message:" + oe.getErrorMessage());
                  System.out.println("Error Code:" + oe.getErrorCode());
                  System.out.println("Request ID:" + oe.getRequestId());
                  System.out.println("Host ID:" + oe.getHostId());
              } catch (ClientException ce) {
                  System.out.println("Caught an ClientException, which means the client encountered "
                          + "a serious internal problem while trying to communicate with OSS, "
                          + "such as not being able to access the network.");
                  System.out.println("Error Message:" + ce.getMessage());
              } finally {
                  if (ossClient != null) {
                      ossClient.shutdown();
                  }
              }
          }
      }