すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:OSS SDK for Javaを使用してOSSリソースへのアクセスを許可する

最終更新日:Nov 01, 2024

このトピックでは、Security Token Service (STS) または署名付きURLによって提供される一時的なアクセス資格情報を使用して、Object Storage Service (OSS) リソースへの一時的なアクセスを許可する方法について説明します。

使用上の注意

  • STSから取得した一時的なアクセス資格情報と署名付きURLには、有効期間を指定する必要があります。 一時的なアクセス資格情報を使用して、オブジェクトのアップロードやダウンロードなどの操作を実行するために使用される署名付きURLを生成する場合、最小有効期間が優先されます。 たとえば、STSによって提供される一時的なアクセス資格情報の有効期間を1,200秒に設定し、資格情報を使用して生成された署名付きURLの有効期間を3,600秒に設定できます。 この場合、署名付きURLが有効期間内であっても、一時アクセス資格情報の有効期限が切れた後は、署名付きURLを使用してオブジェクトをアップロードすることはできません。

  • このトピックでは、アクセス資格情報は環境変数から取得します。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。

  • このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 OSSと同じリージョンにある他のAlibaba Cloudサービスを使用してOSSにアクセスする場合は、https://oss-cn-hangzhou-internal.aliyuncs.com などの内部エンドポイントを使用します。 OSSリージョンとエンドポイントの詳細については、「リージョン、エンドポイント、オープンポート」をご参照ください。

  • このトピックでは、OSSパブリックエンドポイントを使用してOSSClientインスタンスを作成します。 カスタムドメイン名またはSTSを使用してOSSClientインスタンスを作成する場合は、「OSSClientインスタンスの作成」をご参照ください。

STSを使用した一時アクセスの許可

STSを使用して、OSSへの一時アクセスを許可できます。 STSは、ユーザーに一時的なアクセストークンを提供するwebサービスです。 STSを使用して、管理されているサードパーティのアプリケーションまたはRAMユーザーに、カスタムの有効期間とカスタムのアクセス許可を持つ一時的なアクセス資格情報を付与できます。 STSの詳細については、「STSとは何ですか?」をご参照ください。

STSには次の利点があります。

  • 一時的なアクセストークンを生成し、そのアクセストークンをサードパーティのアプリケーションに送信するだけで済みます。 サードパーティのアプリケーションにAccessKeyペアを提供する必要はありません。 このトークンのアクセス権限と有効期間を指定できます。

  • 有効期間が終了すると、トークンは自動的に期限切れになります。 したがって、トークンのアクセス権限を手動で取り消す必要はありません。

STSが提供する一時的なアクセス資格情報を使用してOSSにアクセスするには、次の操作を実行します。

  1. 一時的なアクセス資格情報を取得します。

    一時的なアクセス資格情報には、セキュリティトークンと一時的なAccessKeyペアが含まれます。 AccessKey ペアは、AccessKey ID と AccessKey Secret で構成されます。 一時的なアクセス資格情報の有効期間は秒単位です。 一時的なアクセス資格情報の最小有効期間は900秒です。 一時的なアクセス資格情報の最大有効期間は、現在のロールに指定されている最大セッション期間です。 詳細については、「RAMロールの最大セッション期間の指定」をご参照ください。

    次のいずれかの方法を使用して、一時的なアクセス資格情報を取得できます。

    • 方法 1

      AssumeRole操作を呼び出します。

    • 方法 2

      STS SDKを使用します。 詳細については、「STS SDKの概要」をご参照ください。

  2. 一時的なアクセス資格情報を使用して、オブジェクトをアップロードおよびダウンロードします。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    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";
            // Obtain temporary access credentials from the environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
            String objectName = "exampleobject.txt";
            // Specify the full path of the local file. 
            String pathName = "D:\\localpath\\examplefile.txt";
    
            // After you obtain temporary access credentials from STS, you can use the access credentials to create an OSSClient instance. 
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {            
                // Upload an object. In this example, a local file is uploaded to OSS.             
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(pathName));
                ossClient.putObject(putObjectRequest);
    
                // Download an object to your local computer as a local file. If an existing file has the same name as the downloaded object, the existing file is overwritten by the downloaded object. Otherwise, the downloaded object is saved.             
                //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();
                }
            }
        }
    }

署名付きURLを使用して一時アクセスを許可する

使用上の注意

  • OSS SDKを使用して署名付きURLを生成する場合、OSS SDKはローカルコンピューターに保存されているキー情報に基づいて特定のアルゴリズムを使用して署名を計算し、URLに署名を追加してURLの有効性とセキュリティを確保します。 URLを計算し構築するために実行される操作は、クライアント上で完了する。 ネットワーク経由でサーバーにリクエストを送信する必要はありません。 この方法では、署名付きURLを生成するときに、呼び出し元に特定の権限を付与する必要はありません。 ただし、サードパーティのユーザーが署名付きURLによって承認されたリソースに対して関連する操作を実行できるようにするには、API操作を呼び出して署名付きURLを生成するプリンシパルに対応する権限があることを確認する必要があります。

    たとえば、プリンシパルが署名付きURLを使用してオブジェクトをアップロードする場合は、プリンシパルにoss:PutObject権限を付与する必要があります。 プリンシパルが署名付きURLを使用してオブジェクトをダウンロードまたはプレビューする場合は、プリンシパルにoss:GetObject権限を付与する必要があります。

  • 署名付きURLを生成し、一時的なアクセスのために訪問者にURLを提供できます。 署名付きURLを生成するときに、URLの有効期間を指定して、訪問者が特定のデータにアクセスできる期間を制限できます。

  • HTTPS経由でリソースにアクセスするために使用される署名付きURLを生成するには、エンドポイントのプロトコルをHTTPSに設定します。

  • 次のサンプルコードを使用して生成された署名付きURLには、プラス記号 (+) が含まれる場合があります。 この場合、URLのプラス記号 (+) を % 2Bに置き換えます。 そうでない場合、署名付きURLを使用してオブジェクトにアクセスすることはできません。

次のサンプルコードでは、署名付きURLを生成し、署名付きURLを使用してオブジェクトをアップロードおよびダウンロードする方法の例を示します。

HTTP GETリクエストを許可する署名付きURLの生成

次のサンプルコードは、HTTP GETリクエストを許可する署名付きURLを生成する方法の例を示しています。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import java.net.URL;
import java.util.Date;
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";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
        String objectName = "exampleobject.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Specify the validity period of the signed URL. Unit: milliseconds. In this example, the validity period is set to 1 hour. 
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
            // Generate a signed URL that allows HTTP GET requests. Visitors can enter the URL in a browser to access specific 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();
            }
        }
    }
}

他のHTTPメソッドを使用してリクエストを許可する署名付きURLの生成

オブジェクトのアップロードや削除などの操作を一時的に実行することをユーザーに許可するには、特定のHTTPメソッドを使用してリクエストを許可する署名付きURLを生成する必要があります。 たとえば、HTTP PUT要求がユーザーにオブジェクトのアップロードを許可する署名付きURLを生成できます。

次のサンプルコードは、他のHTTPリクエストメソッドを許可する署名付きURLを生成する方法の例を示しています。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
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 java.util.Date;

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";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
        String objectName = "exampleobject.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
            // Specify the validity period of the signed URL. Unit: milliseconds. In this example, the validity period is set to 1 hour. 
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
            request.setExpiration(expiration);
            // Specify the content type. 
            request.setContentType("text/plain");
            // Specify 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 the content type. Make sure that the content type is the same as the content type that is specified when you generate the signed URL. 
            requestHeaders.put(HttpHeaders.CONTENT_TYPE, "text/plain");
            // Specify 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();
            }
        }
    }
}      

署名付きURLを作成するときにHttpMethod.PUTパラメーターを含めると、許可された訪問者は署名付きURLを使用してオブジェクトをアップロードできます。

特定のパラメータを含む署名付きURLを生成する

  • 特定のパラメータを含む署名付きURLを生成する

    次のサンプルコードは、特定のパラメーターを含む署名付きURLを生成する方法の例を示しています。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.model.GeneratePresignedUrlRequest;
    import java.net.URL;
    import java.util.*;
    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";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
            String objectName = "exampleobject.txt";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a request. 
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
                // Set HttpMethod to PUT. 
                generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
                // Specify user metadata. 
                generatePresignedUrlRequest.addUserMetadata("author", "baymax");
                // Specify the content type. 
                generatePresignedUrlRequest.setContentType("application/txt");
                // Specify the validity period of the signed URL. Unit: milliseconds. In this example, the validity period is set to 1 hour. 
                Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
                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();
                }
            }
        }
    }
  • versionIdパラメーターを含む署名付きURLを生成する

    次のサンプルコードは、versionIdパラメーターを含む署名付きURLを生成する方法の例を示しています。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.model.GeneratePresignedUrlRequest;
    import java.net.URL;
    import java.util.*;
    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";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
    		    // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
            String objectName = "exampleobject.txt";
            // Specify the version ID of the object. 
            String versionId = "CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Create a request. 
                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
                // Set HttpMethod to GET. 
                generatePresignedUrlRequest.setMethod(HttpMethod.GET);
                // Specify the validity period of the signed URL. Unit: milliseconds. In this example, the validity period is set to 1 hour. 
                Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
                generatePresignedUrlRequest.setExpiration(expiration);
                // Specify the version ID of the object. 
                Map<String, String> queryParam = new HashMap<String, String>();
                queryParam.put("versionId", versionId);
                generatePresignedUrlRequest.setQueryParameter(queryParam);
                // 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();
                }
            }
        }
    }

署名付きURLを使用してオブジェクトをアップロードまたはダウンロードする

  • 署名付きURLを使用してシンプルアップロードを使用してオブジェクトをアップロードする

    次のサンプルコードでは、署名付きURLを生成し、署名付きURLを使用してシンプルアップロードを使用してオブジェクトをアップロードする方法の例を示します。

    説明

    OSSコンソールの署名ツールを使用して署名付きURLを作成し、署名付きURLを使用して、単純なアップロードを使用してオブジェクトをアップロードすることをユーザーに許可することもできます。 署名付きURLを生成する方法の詳細については、「URL署名」をご参照ください。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    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.*;
    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";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
            String objectName = "exampleobject.txt";
            // Specify the full path of the local file. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
            String pathName = "D:\\localpath\\examplefile.txt";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
            
            // Specify request headers. 
            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 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. In this example, the validity period is set to 1 hour. 
                Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
    
                // Generate the signed URL. 
                GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
                // Specify the validity period of the signed URL. 
                request.setExpiration(expiration);
    
                // Add headers to the request. 
                request.setHeaders(headers);
                // Specify 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 authorize users to upload the object. In this example, HttpClients is used. 
            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 headers, such as the user metadata and storage class headers, when a signed URL is generated, these headers must be sent to the server when the signed URL is used to upload the local file. If the headers that are sent to the server for the signature calculation are different from the headers specified when the signed URL is generated, 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()){
                    // If userMeta is used, the x-oss-meta- prefix is added to userMeta. If you use other methods to generate a signed URL, the x-oss-meta- prefix is also added to userMeta. 
                    put.addHeader("x-oss-meta-"+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("The object is uploaded by using the network library.");
                }
                System.out.println(response.toString());
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                response.close();
                httpClient.close();
            }
        }
    }       
  • 署名付きURLを使用したマルチパートアップロードによるオブジェクトのアップロード

    署名付きURLを使用してサードパーティアプリケーションにマルチパートアップロードを使用してラージオブジェクトをアップロードする権限を付与する場合は、マルチパートアップロードタスクを開始し、各パートの署名付きURLを生成してから、サードパーティアプリケーションに署名付きURLを提供する必要があります。 このようにして、サードパーティユーザーは署名付きURLを使用してオブジェクトのすべての部分をアップロードし、それらの部分を完全なオブジェクトに結合できます。

    次のサンプルコードでは、マルチパートアップロードを使用して署名付きURLを生成し、署名付きURLを使用してオブジェクトをアップロードする方法の例を示します。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.io.BoundedInputStream;
    import com.aliyun.oss.common.utils.BinaryUtil;
    import com.aliyun.oss.common.utils.CRC64;
    import com.aliyun.oss.internal.OSSHeaders;
    import com.aliyun.oss.model.*;
    import org.apache.commons.codec.digest.DigestUtils;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPut;
    import org.apache.http.entity.BufferedHttpEntity;
    import org.apache.http.entity.InputStreamEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
    import org.apache.http.impl.client.HttpClients;
    import java.io.*;
    import java.math.BigInteger;
    import java.net.URL;
    import java.util.*;
    import java.util.Date;
    import java.util.zip.CheckedInputStream;
    
    public class SignUrlMultipart {
        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";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
            String objectName = "exampleobject.txt";
            // Specify the full path of the local file. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
            String pathName = "D:\\localpath\\examplefile.txt";
            // Specify the validity period of the signed URL. Unit: milliseconds. In this example, the validity period is set to 1 hour. 
            long expireTime = 3600*1000L;
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            // Create an InitiateMultipartUploadRequest object. 
            InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, objectName);
    
            // Initiate the multipart upload task. 
            InitiateMultipartUploadResult upResult = ossClient.initiateMultipartUpload(initRequest);
            // Obtain the upload ID. The upload ID is the unique identifier of the multipart upload task. You can use the upload ID to perform related operations, such as canceling and querying the multipart upload task. 
            String uploadId = upResult.getUploadId();
    
            // partETags is a set of PartETags. A PartETag consists of the part number and ETag of a part. 
            List<PartETag> partETags =  new ArrayList<PartETag>();
            // Specify the part size, which is used to calculate the number of parts of the object. Unit: bytes. 
            long partSize = 1 * 100 * 1024L;   // In this example, the part size is set to 100 KB. 
    
            // Specify the full path of the local file. By default, if you do not specify the full path of a local file, the local file is uploaded from the path of the project to which the sample program belongs. 
            File sampleFile = new File(pathName);
            long fileLength = sampleFile.length();
            // If you want to upload the local file as only one part, set the part size to the local file size. 
            // long fileLength = sampleFile.length();
            int partCount = (int) (fileLength / partSize);
            if (fileLength % partSize != 0) {
                partCount++;
            }
    
            // Specify request headers for the signed URLs. 
            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");*/
    
    
            // Traverse all parts to obtain all signed URLs and upload the parts. 
            // You can also obtain the signed URLs of all parts at a time and then upload the parts. The following sample code provides an example on how to obtain a single signed URL and use the signed URL to upload a part: 
            for (int i = 0; i < partCount; i++) {
                long startPos = i * partSize;
                long curPartSize = (i + 1 == partCount) ?  (fileLength - startPos) : partSize;
    
                /*// Configure MD5 verification. You can perform MD5 verification only for a single part.
                FileInputStream inStream = new FileInputStream(pathName);
                // Skip the parts that are uploaded. 
                inStream.skip(startPos);
                BoundedInputStream entity = new BoundedInputStream(inStream, partSize);
                String md5 = BinaryUtil.toBase64String(DigestUtils.md5(entity));
                headers.put("Content-MD5", md5);*/
    
                String signUrl = getSignUrl(ossClient, bucketName, objectName, HttpMethod.PUT, expireTime, i + 1, uploadId, headers);
    
                // Use the signed URL to upload the part. In this example, HttpClients is used. 
                putObjectWithHttp(signUrl, pathName, startPos, curPartSize, headers);
            }
    
            // If the system for part upload is different from the system for part combination, you must list parts before you can combine the parts. 
            // List the uploaded parts. 
            ListPartsRequest listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId);
            PartListing partListing = ossClient.listParts(listPartsRequest);
    
            // Traverse the parts and populate partETags. 
            for (PartSummary part : partListing.getParts()) {
                PartETag partETag = new PartETag(part.getPartNumber(), part.getETag());
                partETags.add(partETag);
            }
    
            // Combine the parts. 
            CompleteMultipartUploadRequest completeMultipartUploadRequest =
                    new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
            // String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5("aaa".getBytes()));
            // Specify that an existing object that has the same name is not overwritten. 
            // completeMultipartUploadRequest.addHeader("x-oss-forbid-overwrite", "true");
    
            // Complete the multipart upload task. 
            CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
            System.out.println("Parts are combined. The upload task is complete.");
    
    
            // Check whether the uploaded file is complete.
            CRC64 crc = new CRC64();
            InputStream inStream = new FileInputStream(pathName);
            byte[] bytes = new byte[1024];
            int cnt;
            while ((cnt = inStream.read(bytes)) != -1) {
                crc.update(bytes, 0, cnt);
            }
    
            if(crc.getValue() == completeMultipartUploadResult.getServerCRC()){
                System.out.println("File upload is complete");
            } else {
                System.out.println("The uploaded file is incomplete.Handle the exception");
            }
        }
    
        public static void putObjectWithHttp(String signedUrl, String pathName, long startPos, long partSize, Map<String, String> headers) throws IOException {
            CloseableHttpClient httpClient = null;
            CloseableHttpResponse response = null;
            try {
                HttpPut put = new HttpPut(signedUrl);
    
                FileInputStream inStream = new FileInputStream(pathName);
                // Skip the parts that are uploaded. 
                inStream.skip(startPos);
                InputStreamEntity entity = new InputStreamEntity(inStream, partSize);
                BufferedHttpEntity byteArrayEntity = new BufferedHttpEntity(entity);
                put.setEntity(byteArrayEntity);
    
                // If you configure headers, such as the user metadata and storage class headers, when a signed URL is generated, these headers must be sent to the server when the signed URL is used to upload the local file. If the headers that are sent to the server for the signature calculation are different from the headers specified when the signed URL is generated, a signature error is reported. 
                for(Map.Entry header: headers.entrySet()){
                    put.addHeader(header.getKey().toString(),header.getValue().toString());
                }
    
                // Set the number of retries when a request error occurs to 3. The following sample code is used an example to describe how to specify the number of retries when a request error occurs. Specify the number of retries when a request error occurs based on your business requirements.
                httpClient = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)).build();
    
                response = httpClient.execute(put);
    
                System.out.println("Upload status code:"+response.getStatusLine().getStatusCode());
                if(response.getStatusLine().getStatusCode() == 200){
                    System.out.println("The object is uploaded by using the library.");
                }
                System.out.println(response.toString());
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                if(response != null){
                    response.close();
                }
                if(httpClient != null){
                    httpClient.close();
                }
            }
        }
    
        public static String getSignUrl(OSS ossClient, String bucketName, String objectName, HttpMethod method, long expireTime, int partNum, String uploadId, Map<String, String> headers){
            // Specify the validity period of the signed URL. Unit: milliseconds. 
            Date expiration = new Date(new Date().getTime() + expireTime);
    
            // Generate the signed URL. 
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, method);
            // Specify the validity period of the signed URL. 
            request.setExpiration(expiration);
    
            // Add headers to the request. 
            request.setHeaders(headers);
    
            request.addQueryParameter("partNumber", String.valueOf(partNum));
    
            request.addQueryParameter("uploadId", uploadId);
    
    
            // Generate the signed URL that allows HTTP requests. 
            URL signedUrl = ossClient.generatePresignedUrl(request);
            // Display the signed URL. 
            System.out.println("signed url: " + signedUrl);
            return signedUrl.toString();
        }
    }
  • 署名付き URL を使用してオブジェクトをダウンロード

    次のサンプルコードは、署名付きURLを使用してオブジェクトをダウンロードする方法の例を示しています。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    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.*;
    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";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Example: exampleobject.txt. Do not include the bucket name in the full path of the object. 
            String objectName = "exampleobject.txt";
            // Specify the local path to which you want to download the object. 
            String pathName = "D:\\localpath\\examplefile.txt";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
          
            // Specify request headers. 
            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 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. In this example, the validity period is set to 1 hour. 
                Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
    
                // Generate the signed URL. 
                GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
                // Specify the validity period of the signed URL. 
                request.setExpiration(expiration);
    
                // Add headers to the request. 
                request.setHeaders(headers);
                // Specify user metadata. 
                request.setUserMetadata(userMetadata);
    
                // Specify query parameters. 
                // Map<String, String> queryParam = new HashMap<String, String>();
                // Specify the IP address or CIDR block, which is the value of the sourceIpFromSource field in the log. 
                // queryParam.put("x-oss-ac-source-ip","192.0.2.0");
                // Convert the subnet mask to binary and then enter the number of 1s in the result. 
                // queryParam.put("x-oss-ac-subnet-mask","32");
                // Specify the ID of the virtual private cloud (VPC). 
                // 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. In this example, HttpClients is used. 
            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 headers, 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 the headers that are sent to the server for the signature calculation are different from the headers specified when the signed URL is generated, 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()){
                    // If userMeta is used, the x-oss-meta- prefix is added to userMeta. When you use other methods to generate a signed URL for object download, the x-oss-meta- prefix is also added to userMeta. 
                    get.addHeader("x-oss-meta-"+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("The object is downloaded by 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();
            }
        }
    }

よくある質問

署名付きURLを使用してローカルファイルをアップロードする場合、アップロード中に署名付きURLの有効期限が切れた場合、ファイルはアップロードされますか?

シンプルアップロードを使用すると、アップロード中に署名付きURLの有効期限が切れても、ファイルは引き続きアップロードされます。

マルチパートアップロードを使用する場合、パーツの署名付きURLがアップロード中に期限切れになると、残りのパーツはアップロードされない場合があります。