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

Object Storage Service:署名付き URL を使用したオブジェクトのダウンロード (Java SDK V1)

最終更新日:Dec 17, 2025

デフォルトでは、Object Storage Service (OSS) バケット内のオブジェクトは非公開です。オブジェクト所有者のみがアクセスできます。OSS SDK for Java を使用して、GET リクエスト用の署名付き URL を生成できます。この URL には有効期限が含まれており、第三者が一時的にオブジェクトをダウンロードすることを許可します。URL は有効期間内であれば複数回使用できます。URL の有効期限が切れた後は、新しい URL を生成する必要があります。

注意事項

  • このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。同じリージョン内の他の Alibaba Cloud サービスから OSS にアクセスするには、内部エンドポイントを使用します。サポートされているリージョンとエンドポイントの詳細については、「リージョンとエンドポイント」をご参照ください。

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

  • このトピックでは、OSS エンドポイントを使用して OSSClient インスタンスを作成します。カスタムドメイン名またはセキュリティトークンサービス (STS) を使用して OSSClient インスタンスを作成する場合は、「一般的なシナリオの設定例」をご参照ください。

  • 署名付き URL の生成に権限は必要ありません。ただし、第三者が署名付き URL を使用してオブジェクトをダウンロードするには、URL を生成するユーザーが oss:GetObject 権限を持っている必要があります。権限の付与方法の詳細については、「RAM ユーザーへのカスタム権限の付与」をご参照ください。

  • このトピックでは、V4 署名付き URL を例として使用します。最大有効期間は 7 日間です。詳細については、「署名バージョン 4 (推奨)」をご参照ください。

操作手順

以下の手順では、署名付き URL を使用してオブジェクトをダウンロードする方法について説明します。

コード例

  1. オブジェクト所有者が GET リクエスト用の署名付き URL を生成します。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.common.comm.SignVersion;
    
    import java.net.URL;
    import java.util.Date;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // この例では、中国 (杭州) リージョンのパブリックエンドポイントを使用します。実際のエンドポイントを指定してください。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // バケット名を入力します。例:examplebucket。
            String bucketName = "examplebucket";
            // オブジェクトの完全なパスを入力します。例:exampleobject.txt。完全なパスにバケット名を含めることはできません。
            String objectName = "exampleobject.txt";
            // バケットが配置されているリージョンを入力します。たとえば、バケットが中国 (杭州) リージョンにある場合は、Region を cn-hangzhou に設定します。
            String region = "cn-hangzhou";
    
            // OSSClient インスタンスを作成します。
            // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            OSS ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();
    
            try {
                // 署名付き URL の有効期限をミリ秒単位で設定します。この例では、有効期限を 1 時間に設定します。
                Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
                // GET リクエスト用の署名付き URL を生成します。この例には、追加のリクエストヘッダーは含まれていません。他のユーザーはブラウザ経由で直接コンテンツにアクセスできます。
                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();
                }
            }
        }
    }
  2. 他のユーザーが署名付き URL を使用してオブジェクトをダウンロードします。

    curl

    curl -SO "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"

    Java

    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class Demo {
        public static void main(String[] args) {
            // 生成された GET リクエスト用の署名付き URL に置き換えます。
            String fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
            // ファイルを保存する宛先パスを、ファイル名と拡張子を含めて入力します。
            String savePath = "C:/downloads/myfile.txt";
    
            try {
                downloadFile(fileURL, savePath);
                System.out.println("Download completed!");
            } catch (IOException e) {
                System.err.println("Error during download: " + e.getMessage());
            }
        }
    
        private static void downloadFile(String fileURL, String savePath) throws IOException {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
    
            // レスポンスコードを確認します。
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 入力ストリーム。
                InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                // 出力ストリーム。
                FileOutputStream outputStream = new FileOutputStream(savePath);
    
                byte[] buffer = new byte[4096]; // バッファー。
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
    
                outputStream.close();
                inputStream.close();
            } else {
                System.out.println("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();
        }
    }

    Node.js

    const https = require('https');
    const fs = require('fs');
    
    const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
    const savePath = "C:/downloads/myfile.txt";
    
    https.get(fileURL, (response) => {
        if (response.statusCode === 200) {
            const fileStream = fs.createWriteStream(savePath);
            response.pipe(fileStream);
            
            fileStream.on('finish', () => {
                fileStream.close();
                console.log("Download completed!");
            });
        } else {
            console.error(`Download failed. Server responded with code: ${response.statusCode}`);
        }
    }).on('error', (err) => {
        console.error("Error during download:", err.message);
    });

    Python

    import requests
    
    file_url = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"
    save_path = "C:/downloads/myfile.txt"
    
    try:
        response = requests.get(file_url, stream=True)
        if response.status_code == 200:
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(4096):
                    f.write(chunk)
            print("Download completed!")
        else:
            print(f"No file to download. Server replied HTTP code: {response.status_code}")
    except Exception as e:
        print("Error during download:", e)

    Go

    package main
    
    import (
        "io"
        "net/http"
        "os"
    )
    
    func main() {
        fileURL := "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"
        savePath := "C:/downloads/myfile.txt"
    
        response, err := http.Get(fileURL)
        if err != nil {
            panic(err)
        }
        defer response.Body.Close()
    
        if response.StatusCode == http.StatusOK {
            outFile, err := os.Create(savePath)
            if err != nil {
                panic(err)
            }
            defer outFile.Close()
    
            _, err = io.Copy(outFile, response.Body)
            if err != nil {
                panic(err)
            }
            println("Download completed!")
        } else {
            println("No file to download. Server replied HTTP code:", response.StatusCode)
        }
    }

    JavaScript

    const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
    const savePath = "C:/downloads/myfile.txt"; // ダウンロードに使用するファイル名。
    
    fetch(fileURL)
        .then(response => {
            if (!response.ok) {
                throw new Error(`Server replied HTTP code: ${response.status}`);
            }
            return response.blob(); // レスポンスを blob に変換します。
        })
        .then(blob => {
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = savePath; // ダウンロードされるファイルの名前を設定します。
            document.body.appendChild(link); // この手順により、リンクがドキュメント内に存在することが保証されます。
            link.click(); // ダウンロードリンクのクリックをシミュレートします。
            link.remove(); // 完了後にリンクを削除します。
            console.log("Download completed!");
        })
        .catch(error => {
            console.error("Error during download:", error);
        });

    Android-Java

    import android.os.AsyncTask;
    import android.os.Environment;
    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class DownloadTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            String fileURL = params[0];
            String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/myfile.txt"; // 変更された保存パス。
            try {
                URL url = new URL(fileURL);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setRequestMethod("GET");
                int responseCode = httpConn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                    FileOutputStream outputStream = new FileOutputStream(savePath);
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    outputStream.close();
                    inputStream.close();
                    return "Download completed!";
                } else {
                    return "No file to download. Server replied HTTP code: " + responseCode;
                }
            } catch (Exception e) {
                return "Error during download: " + e.getMessage();
            }
        }
    }

    Objective-C

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // ファイル URL と保存パスを定義します (有効なパスに変更してください)。
            NSString *fileURL = @"https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
            NSString *savePath = @"/Users/your_username/Desktop/myfile.txt"; // ご利用のユーザー名に置き換えてください。
            
            // URL オブジェクトを作成します。
            NSURL *url = [NSURL URLWithString:fileURL];
            
            // ダウンロードタスクを作成します。
            NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                // エラー処理。
                if (error) {
                    NSLog(@"Error during download: %@", error.localizedDescription);
                    return;
                }
                
                // データを確認します。
                if (!data) {
                    NSLog(@"No data received.");
                    return;
                }
                
                // ファイルを保存します。
                NSError *writeError = nil;
                BOOL success = [data writeToURL:[NSURL fileURLWithPath:savePath] options:NSDataWritingAtomic error:&writeError];
                if (success) {
                    NSLog(@"Download completed!");
                } else {
                    NSLog(@"Error saving file: %@", writeError.localizedDescription);
                }
            }];
            
            // タスクを開始します。
            [task resume];
            
            // 非同期リクエストが完了できるように、メインスレッドを実行し続けます。
            [[NSRunLoop currentRunLoop] run];
        }
        return 0;
    }

その他のシナリオ

特定のファイルバージョンの署名付き URL の生成

以下のコード例は、オブジェクトの特定のバージョンをダウンロードするための GET リクエスト用の署名付き URL を生成する方法を示しています。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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 {
        // この例では、中国 (杭州) リージョンのパブリックエンドポイントを使用します。実際のエンドポイントを指定してください。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
	// バケット名を入力します。例:examplebucket。
        String bucketName = "examplebucket";
        // オブジェクトの完全なパスを入力します。例:exampleobject.txt。完全なパスにバケット名を含めることはできません。
        String objectName = "exampleobject.txt";
        // オブジェクトの versionId を入力します。
        String versionId = "CAEQARiBgID8rumR2hYiIGUyOTAyZGY2MzU5MjQ5ZjlhYzQzZjNlYTAyZDE3****";
        // バケットが配置されているリージョンを入力します。たとえば、バケットが中国 (杭州) リージョンにある場合は、Region を cn-hangzhou に設定します。
        String region = "cn-hangzhou";

        // OSSClient インスタンスを作成します。
        // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // リクエストを作成します。
            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, objectName);
            // HttpMethod を GET に設定します。
            generatePresignedUrlRequest.setMethod(HttpMethod.GET);
            // 署名付き URL の有効期限をミリ秒単位で設定します。この例では、有効期限を 1 時間に設定します。
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);
            generatePresignedUrlRequest.setExpiration(expiration);
            // オブジェクトの versionId。
            Map<String, String> queryParam = new HashMap<String, String>();
            queryParam.put("versionId", versionId);
            generatePresignedUrlRequest.setQueryParameter(queryParam);
            // 署名付き 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 の生成

以下のコード例は、カスタムドメイン名を使用して GET リクエスト用の署名付き URL を生成する方法を示しています。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;

import java.net.URL;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // yourCustomEndpoint をカスタムドメイン名に設定します。例:http://static.example.com。
        String endpoint = "yourCustomEndpoint";
        // バケットのリージョン情報を入力します。例:cn-hangzhou。
        String region = "cn-hangzhou";
        // バケット名を入力します。例:examplebucket。
        String bucketName = "examplebucket";
        // オブジェクトの完全なパスを入力します。例:exampleobject.txt。完全なパスにバケット名を含めることはできません。
        String objectName = "exampleobject.txt";

        // 環境変数からアクセス認証情報を取得します。このコードを実行する前に、環境変数を設定してください。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // OSSClient インスタンスを作成します。
        // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 注:CNAME オプションを有効にするには、これを true に設定します。
        clientBuilderConfiguration.setSupportCname(true);
        // V4 署名アルゴリズムの使用を明示的に宣言します。
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 生成された署名付き URL の有効期限をミリ秒単位で設定します。この例では、有効期限を 1 時間に設定します。
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);

            // 署名付き URL を生成します。
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);

            // 有効期限を設定します。
            request.setExpiration(expiration);

            // HTTP GET リクエスト用の署名付き URL を生成します。
            URL signedUrl = ossClient.generatePresignedUrl(request);
            // 署名付き URL を出力します。
            System.out.println("signed url for getObject: " + 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());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

強制ダウンロード用署名付き URL の生成

カスタムドメイン名を使用して OSS にアクセスする場合、または 2022 年 10 月 9 日 00:00 より前に OSS を有効にした場合、URL を使用してアクセスすると、オブジェクトはデフォルトでプレビューされます。ダウンロードを強制するには、レスポンスヘッダーに `Content-Disposition: attachment` を追加します。

以下の例は、カスタムドメイン名を使用する際にダウンロードを強制する方法を示しています。同じ方法がデフォルトの OSS ドメイン名にも適用されます。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;

import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // カスタムドメイン名を入力します。例:http://static.example.com。
        String endpoint = "http://static.example.com";
        // 環境変数からアクセス認証情報を取得します。このコードを実行する前に、OSS_ACCESS_KEY_ID および OSS_ACCESS_KEY_SECRET 環境変数が設定されていることを確認してください。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // バケット名を入力します。例:examplebucket。
        String bucketName = "examplebucket";
        // オブジェクトの完全なパスを入力します。例:exampleobject.txt。完全なパスにバケット名を含めることはできません。
        String objectName = "exampleobject.txt";

        // OSSClient インスタンスを作成します。
        // OSSClient インスタンスが不要になったら、shutdown メソッドを呼び出してリソースを解放します。
        String region = "cn-hangzhou";
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 注:カスタムドメイン名を使用する場合は、CNAME を true に設定する必要があります。
        clientBuilderConfiguration.setSupportCname(true);

        //V4 署名アルゴリズムを設定します。
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        URL signedUrl = null;
        try {
            // 生成された署名付き URL の有効期限をミリ秒単位で設定します。この例では、有効期限を 1 時間に設定します。
            Date expiration = new Date(new Date().getTime() + 3600 * 1000L);

            // ダウンロード時にクライアントに表示されるファイル名を定義します。この例では "homework.txt" を使用します。
            String filename = "homework.txt";

            // 署名付き URL を生成します。
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);

            // ダウンロード動作 (プレビューではなく強制ダウンロード) とファイル名を設定します。
            request.getResponseHeaders().setContentDisposition("attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));

            // 有効期限を設定します。
            request.setExpiration(expiration);

            // HTTP GET リクエスト用の署名付き URL を生成します。
            signedUrl = ossClient.generatePresignedUrl(request);
            // 署名付き URL を出力します。
            System.out.println("signed url for getObject: " + 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());
        }
    }

}

関連ドキュメント

  • 署名付き URL を使用してオブジェクトをダウンロードするための完全なサンプルコードについては、GitHub の例をご参照ください。

  • 署名付き URL を生成するために使用される API 操作の詳細については、GeneratePresignedUrlRequest をご参照ください。