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.

To access OSS by using temporary access credentials provided by STS, perform the following operations:

  1. Obtain temporary access credentials

    The temporary access credentials consist of an 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.

    You can use one of the following methods to obtain temporary access credentials.

    • Method 1

      You can call the AssumeRole operation to obtain temporary access credentials.

    • Method 2

      You can use STS SDKs to obtain temporary access credentials. For more information, see STS SDK overview.

  2. Upload an object by using the temporary access credentials obtained from STS
    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 full path cannot contain the bucket name. 
            //String objectName = "exampleobject.txt";
            //String pathName = "D:\\localpath\\examplefile.txt";
    
            // Use the temporary access credentials obtained from STS 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 you do not specify the local path for the downloaded object, 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();
                }
            }
        }
    }

Use a signed URL for temporary access authorization

This section provides examples on how to use 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 full path cannot contain the bucket name. 
            String objectName = "exampleobject.txt";
    
            // Use the temporary access credentials obtained from STS 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 a signed URL that can be used to perform GET operations. 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 full 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"};
    
            // Use the temporary access credentials obtained from STS 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);
    
                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 full path cannot contain the bucket name. 
            String objectName = "exampleobject.txt";
    
            // Use the temporary access credentials obtained from STS 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 full 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"};
    
            // Use the temporary access credentials obtained from STS 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 full path cannot contain the bucket name. 
            String objectName = "exampleobject.txt";
    
            // Use the temporary access credentials obtained from STS 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 URL. 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 full 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"};
    
            // Use the temporary access credentials obtained from STS 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 sample code provides an example on how to use a signed URL to upload an object:

    import com.aliyun.oss.*;
    import com.aliyun.oss.internal.OSSHeaders;
    import com.aliyun.oss.model.GeneratePresignedUrlRequest;
    import com.aliyun.oss.model.StorageClass;
    import org.apache.http.HttpEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.entity.FileEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import java.io.*;
    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 full 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. 
            // Use the temporary access credentials from STS to create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
            // Do not use the temporary access credentials from STS to create an OSSClient instance. 
            // OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            // Specify the request header. 
            Map<String, String> headers = new HashMap<String, String>();
            /*// Specify the storage class of the object. 
            headers.put(OSSHeaders.STORAGE_CLASS, StorageClass.Standard.toString());
            // Specify the content type. 
            headers.put(OSSHeaders.CONTENT_TYPE, "text/txt");*/
    
            // Specify custom user metadata. 
            Map<String, String> userMetadata = new HashMap<String, String>();
            /*userMetadata.put("key1","value1");
            userMetadata.put("key2","value2");*/
    
            URL signedUrl = null;
            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);
    
                // Add the header to the request. 
                request.setHeaders(headers);
                // Specify custom user metadata. 
                request.setUserMetadata(userMetadata);
    
                // Generate a signed URL that allows HTTP PUT requests. 
                signedUrl = ossClient.generatePresignedUrl(request);
                // Display the signed URL. 
                System.out.println("signed url for putObject: " + signedUrl);
    
            } 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());
            }
    
            // Use the signed URL to upload an object. HttpClients is used as an example. 
            putObjectWithHttp(signedUrl, pathName, headers, userMetadata);
        }
    
        public static void putObjectWithHttp(URL signedUrl, String pathName, Map<String, String> headers, Map<String, String> userMetadata) throws IOException {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            try {
                HttpPut put = new HttpPut(signedUrl.toString());
                HttpEntity entity = new FileEntity(new File(pathName));
                put.setEntity(entity);
                // If you configure header parameters such as user metadata and storage class when a signed URL is generated, you must send these parameters to the server when you call the signed URL to upload the object. If parameters for the signature is inconsistent with those sent to the server, a signature error is reported. 
                for(Map.Entry header: headers.entrySet()){
                    put.addHeader(header.getKey().toString(),header.getValue().toString());
                }
                for(Map.Entry meta: userMetadata.entrySet()){
                    put.addHeader(meta.getKey().toString(),meta.getValue().toString());
                }
    
                httpClient = HttpClients.createDefault();
    
                response = httpClient.execute(put);
    
                System.out.println("Upload status code:"+response.getStatusLine().getStatusCode());
                if(response.getStatusLine().getStatusCode() == 200){
                    System.out.println("Upload successfully using the network library");
                }
                System.out.println(response.toString());
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                response.close();
                httpClient.close();
            }
        }
    }       
  • Use a signed URL to download an object

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

    import com.aliyun.oss.*;
    import com.aliyun.oss.internal.OSSHeaders;
    import com.aliyun.oss.model.GeneratePresignedUrlRequest;
    import com.aliyun.oss.model.StorageClass;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import java.io.*;
    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 full path cannot contain the bucket name. 
            String objectName = "exampleobject.txt";
            // Specify the full path of the local file to which you want to download the object. 
            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. 
            // Use the temporary access credentials from STS to create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
            // Do not use the temporary access credentials from STS to create an OSSClient instance. 
            // OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            // Specify the request header. 
            Map<String, String> headers = new HashMap<String, String>();
            /*// Specify the storage class of the object. 
            headers.put(OSSHeaders.STORAGE_CLASS, StorageClass.Standard.toString());
            // Specify the content type. 
            headers.put(OSSHeaders.CONTENT_TYPE, "text/txt");*/
    
            // Specify custom user metadata. 
            Map<String, String> userMetadata = new HashMap<String, String>();
            /*userMetadata.put("key1","value1");
            userMetadata.put("key2","value2");*/
    
            URL signedUrl = null;
            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);
    
                // Add the header to the request. 
                request.setHeaders(headers);
                // Specify custom user metadata. 
                request.setUserMetadata(userMetadata);
    
                // Specify query parameters. 
                // Map<String, String> queryParam = new HashMap<String, String>();
                // Specify the IP address or CIDR block. 
                // queryParam.put("x-oss-ac-source-ip","110.191.179.0");
                // Specify the number of the digit 1 in the subnet mask. 
                // queryParam.put("x-oss-ac-subnet-mask","32");
                // Specify the VPC ID. 
                // queryParam.put("x-oss-ac-vpc-id","vpc-12345678");
                // Specify whether the request can be forwarded. 
                // queryParam.put("x-oss-ac-forward-allow","true");
                // request.setQueryParameter(queryParam);
    
                // Configure single-connection bandwidth throttling, such as 100 KB/s. Unit: bit/s. 
                // request.setTrafficLimit(100 * 1024 * 8);
    
                // Generate a signed URL that allows HTTP GET requests. 
                signedUrl = ossClient.generatePresignedUrl(request);
                // Display the signed URL. 
                System.out.println("signed url for putObject: " + signedUrl);
            } 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());
            }
    
            // Use the signed URL to download an object. HttpClients is used as an example. 
            getObjectWithHttp(signedUrl, pathName, headers, userMetadata);
        }
    
        public static void getObjectWithHttp(URL signedUrl, String pathName, Map<String, String> headers, Map<String, String> userMetadata) throws IOException {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            try {
                HttpGet get = new HttpGet(signedUrl.toString());
    
                // If you configure header parameters such as user metadata and storage class when a signed URL is generated, you must send these parameters to the server when you call the signed URL to download the object. If parameters for the signature is inconsistent with those sent to the server, a signature error is reported. 
                for(Map.Entry header: headers.entrySet()){
                    get.addHeader(header.getKey().toString(),header.getValue().toString());
                }
                for(Map.Entry meta: userMetadata.entrySet()){
                    get.addHeader(meta.getKey().toString(),meta.getValue().toString());
                }
    
                httpClient = HttpClients.createDefault();
                response = httpClient.execute(get);
    
                System.out.println("Download status code:"+response.getStatusLine().getStatusCode());
                if(response.getStatusLine().getStatusCode() == 200){
                    System.out.println("Download successfully using the network library");
                }
                System.out.println(response.toString());
    
                // Save the object to the disk. 
                saveFileToLocally(response.getEntity().getContent(), pathName);
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                response.close();
                httpClient.close();
            }
        }
    
        public static void saveFileToLocally(InputStream inputStream, String pathName) throws IOException {
            DataInputStream in = null;
            OutputStream out = null;
            try {
                in = new DataInputStream(inputStream);
                out = new DataOutputStream(new FileOutputStream(pathName));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                in.close();
                out.close();
            }
        }
    }