You need to enable JavaScript to run this app.
导航
普通预签名(Java SDK)
最近更新时间:2024.02.04 18:30:53首次发布时间:2021.11.27 17:58:44

TOSV2Client 在向服务端发起请求时,默认会对请求 header 里包含签名。SDK 也支持构造带签名的 URL,您可直接用该 URL 发起 HTTP 请求,也可以将该 URL 共享给第三方实现访问授权。本文介绍普通预签名的相应示例。

生成用于下载的预签名 URL 示例

以下代码展示如何生成一个以 GET 方法访问的预签名 URL。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.comm.HttpMethod;
import com.volcengine.tos.model.object.PreSignedURLInput;
import com.volcengine.tos.model.object.PreSignedURLOutput;

public class PreSignedUrlGetObjectExample {
    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        String objectKey = "example_dir/example_object.txt";
        // 单位为秒,设置3600秒即1小时后过期
        long expires = 3600;

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        try{
            PreSignedURLInput input = new PreSignedURLInput().setBucket(bucketName).setKey(objectKey)
                    .setHttpMethod(HttpMethod.GET).setExpires(expires);
            PreSignedURLOutput output = tos.preSignedURL(input);
            System.out.println("preSignedURL succeed, the signed url is " + output.getSignedUrl());
            System.out.println("preSignedURL succeed, the signed header is " + output.getSignedHeader());
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("preSignedURL failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("preSignedURL failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }
}

生成用于上传的预签名 URL 示例

以下代码展示如何生成一个以 PUT 方法访问的预签名 URL。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.comm.HttpMethod;
import com.volcengine.tos.model.object.PreSignedURLInput;
import com.volcengine.tos.model.object.PreSignedURLOutput;

public class PreSignedUrlPutObjectExample {
    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        String objectKey = "example_dir/example_object.txt";
        // 单位为秒,设置3600秒即1小时后过期
        long expires = 3600;

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        try{
            PreSignedURLInput input = new PreSignedURLInput().setBucket(bucketName).setKey(objectKey)
                    .setHttpMethod(HttpMethod.PUT).setExpires(expires);
            PreSignedURLOutput output = tos.preSignedURL(input);
            System.out.println("preSignedURL succeed, the signed url is " + output.getSignedUrl());
            System.out.println("preSignedURL succeed, the signed header is " + output.getSignedHeader());
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("preSignedURL failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("preSignedURL failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }
}

使用预签名 URL 上传对象示例

以下代码展示如何用生成的预签名 URL 上传对象,以 okhttp client 为例。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.comm.HttpMethod;
import com.volcengine.tos.model.object.PreSignedURLInput;
import com.volcengine.tos.model.object.PreSignedURLOutput;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class PreSignedUrlPutObjectWithRequestExample {
    // 建议使用时将 OkHttpClient 设置为静态单例对象
    private static OkHttpClient client;

    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        String objectKey = "example_dir/example_object.txt";
        // 单位为秒,设置3600秒即1小时后过期
        long expires = 3600;

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        try{
            PreSignedURLInput input = new PreSignedURLInput().setBucket(bucketName).setKey(objectKey)
                    .setHttpMethod(HttpMethod.PUT).setExpires(expires);
            PreSignedURLOutput output = tos.preSignedURL(input);
            System.out.println("preSignedURL succeed, the signed url is " + output.getSignedUrl());
            System.out.println("preSignedURL succeed, the signed header is " + output.getSignedHeader());
            doPutObject(output.getSignedUrl(), "Hello Volcengine TOS.");
        } catch (IOException e) {
            System.out.println("putObject failed");
            e.printStackTrace();
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("preSignedURL failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("preSignedURL failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }

    private static void doPutObject(String url, String content) throws IOException {
        if (client == null) {
            ConnectionPool connectionPool = new ConnectionPool(1024, 60000, TimeUnit.MILLISECONDS);
            Dispatcher dispatcher = new Dispatcher();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            client = builder.dispatcher(dispatcher)
                    .connectionPool(connectionPool).retryOnConnectionFailure(true).connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .readTimeout(30000, TimeUnit.MILLISECONDS).writeTimeout(30000, TimeUnit.MILLISECONDS)
                    .followRedirects(false).followSslRedirects(false).build();
        }
        Request.Builder builder = new Request.Builder().url(url);
        builder.put(RequestBody.create(MediaType.parse("binary/octet-stream"), content));
        Response response = null;
        try{
            response = client.newCall(builder.build()).execute();
        } finally{
            if (response != null) {
                response.close();
            }
        }
    }
}

使用预签名 URL 下载对象示例

以下代码展示如何用生成的预签名 URL 下载对象,以 okhttp client 为例。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.comm.HttpMethod;
import com.volcengine.tos.model.object.PreSignedURLInput;
import com.volcengine.tos.model.object.PreSignedURLOutput;
import com.volcengine.tos.model.object.PutObjectInput;
import okhttp3.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class PreSignedUrlGetObjectWithRequestExample {
    // 建议使用时将 OkHttpClient 设置为静态单例对象
    private static OkHttpClient client;

    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        String objectKey = "example_dir/example_object.txt";
        // 单位为秒,设置3600秒即1小时后过期
        long expires = 3600;

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        try{
            // 先上传数据
            tos.putObject(new PutObjectInput().setBucket(bucketName).setKey(objectKey)
                    .setContent(new ByteArrayInputStream("Hello Volcengine TOS.".getBytes())));

            PreSignedURLInput input = new PreSignedURLInput().setBucket(bucketName).setKey(objectKey)
                    .setHttpMethod(HttpMethod.GET).setExpires(expires);
            PreSignedURLOutput output = tos.preSignedURL(input);
            System.out.println("preSignedURL succeed, the signed url is " + output.getSignedUrl());
            System.out.println("preSignedURL succeed, the signed header is " + output.getSignedHeader());
            String content = doGetObject(output.getSignedUrl());
            System.out.println("getObject to String succeed, the content is " + content);
        } catch (IOException e) {
            System.out.println("getObject to String failed");
            e.printStackTrace();
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("preSignedURL failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("preSignedURL failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }

    private static String doGetObject(String url) throws IOException {
        if (client == null) {
            ConnectionPool connectionPool = new ConnectionPool(1024, 60000, TimeUnit.MILLISECONDS);
            Dispatcher dispatcher = new Dispatcher();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            client = builder.dispatcher(dispatcher)
                    .connectionPool(connectionPool).retryOnConnectionFailure(true).connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .readTimeout(30000, TimeUnit.MILLISECONDS).writeTimeout(30000, TimeUnit.MILLISECONDS)
                    .followRedirects(false).followSslRedirects(false).build();
        }
        Request.Builder builder = new Request.Builder().url(url);
        Response response = client.newCall(builder.get().build()).execute();
        if (response == null || response.body() == null) {
            return null;
        }
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = response.body().byteStream().read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        result.flush();
        return result.toString("UTF-8");
    }
}

生成用于执行图片处理的预签名 URL 示例

以下代码展示如何用生成的预签名 URL 执行图片处理,以 okhttp client 为例。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.comm.HttpMethod;
import com.volcengine.tos.comm.TosHeader;
import com.volcengine.tos.model.object.PreSignedURLInput;
import com.volcengine.tos.model.object.PreSignedURLOutput;
import okhttp3.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class PreSignedUrlImageProcessWithRequestExample {
    // 建议使用时将 OkHttpClient 设置为静态单例对象
    private static OkHttpClient client;

    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        // 需要确保待处理的对象已存在
        String objectKey = "image.png";
        String filePath = "example_dir/image.jpg";

        String style = "image/resize,h_100/format,jpg"; //将图片高度固定为 100px,并转为 JPG 格式
        Map<String, String> query = new HashMap<>();
        query.put(TosHeader.QUERY_DATA_PROCESS, style);
        // 单位为秒,设置3600秒即1小时后过期
        long expires = 3600;

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        try {
            PreSignedURLInput input = new PreSignedURLInput().setBucket(bucketName).setKey(objectKey).setQuery(query)
                    .setHttpMethod(HttpMethod.GET).setExpires(expires);
            PreSignedURLOutput output = tos.preSignedURL(input);
            System.out.println("preSignedURL succeed, the signed url is " + output.getSignedUrl());
            System.out.println("preSignedURL succeed, the signed header is " + output.getSignedHeader());
            doGetObject(output.getSignedUrl(), filePath);
        } catch (IOException e) {
            System.out.println("getObject to String failed");
            e.printStackTrace();
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("preSignedURL failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("preSignedURL failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }

    private static void doGetObject(String url, String filePath) throws IOException {
        if (client == null) {
            ConnectionPool connectionPool = new ConnectionPool(1024, 60000, TimeUnit.MILLISECONDS);
            Dispatcher dispatcher = new Dispatcher();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            client = builder.dispatcher(dispatcher)
                    .connectionPool(connectionPool).retryOnConnectionFailure(true).connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .readTimeout(30000, TimeUnit.MILLISECONDS).writeTimeout(30000, TimeUnit.MILLISECONDS)
                    .followRedirects(false).followSslRedirects(false).build();
        }
        Request.Builder builder = new Request.Builder().url(url);
        Response response = client.newCall(builder.get().build()).execute();
        if (response == null || response.body() == null) {
            System.out.println("image process failed");
            return;
        }

        // 以下代码展示如何将转码后的图片数据下载到本地。
        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath);
             InputStream output = response.body().byteStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = output.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, length);
            }
            System.out.println("image process succeed");
        } catch (IOException e) {
            System.out.println("write data to file failed");
            e.printStackTrace();
        }
    }
}

生成用于执行文档预览的预签名 URL 示例

以下代码展示如何用生成的预签名 URL 执行文档预览,以 okhttp client 为例。

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.TOSV2ClientBuilder;
import com.volcengine.tos.TosClientException;
import com.volcengine.tos.comm.HttpMethod;
import com.volcengine.tos.comm.TosHeader;
import com.volcengine.tos.model.object.PreSignedURLInput;
import com.volcengine.tos.model.object.PreSignedURLOutput;
import okhttp3.OkHttpClient;

import java.util.HashMap;
import java.util.Map;

public class PreSignedUrlDocProcessWithRequestExample {
    // 建议使用时将 OkHttpClient 设置为静态单例对象
    private static OkHttpClient client;

    public static void main(String[] args) {
        String endpoint = "your endpoint";
        String region = "your region";
        String accessKey = System.getenv("TOS_ACCESS_KEY");
        String secretKey = System.getenv("TOS_SECRET_KEY");

        String bucketName = "bucket-example";
        // 需要确保待处理的对象已存在
        String objectKey = "image.png";

        String style = "doc-preview"; //标记为文档预览的请求
        String sourceType = "docx";  // 原始文档类型为docx
        String destType = "jpg";   //预览类型为jpg
        String docPage = "1";  //处理页码
        Map<String, String> query = new HashMap<>();
        query.put(TosHeader.QUERY_DATA_PROCESS, style);
        query.put("x-tos-doc-src-type", sourceType);
        query.put("x-tos-doc-dst-type", destType);
        query.put("x-tos-doc-page", docPage);

        // 单位为秒,设置3600秒即1小时后过期
        long expires = 3600;

        TOSV2 tos = new TOSV2ClientBuilder().build(region, endpoint, accessKey, secretKey);

        try {
            PreSignedURLInput input = new PreSignedURLInput().setBucket(bucketName).setKey(objectKey).setQuery(query)
                    .setHttpMethod(HttpMethod.GET).setExpires(expires);
            PreSignedURLOutput output = tos.preSignedURL(input);
            System.out.println("preSignedURL succeed, the signed url is " + output.getSignedUrl());
            System.out.println("preSignedURL succeed, the signed header is " + output.getSignedHeader());
        } catch (TosClientException e) {
            // 操作失败,捕获客户端异常,一般情况是请求参数错误,此时请求并未发送
            System.out.println("preSignedURL failed");
            System.out.println("Message: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
        } catch (Throwable t) {
            // 作为兜底捕获其他异常,一般不会执行到这里
            System.out.println("preSignedURL failed");
            System.out.println("unexpected exception, message: " + t.getMessage());
        }
    }
}

相关文档

关于 URL 包含签名的详细信息,请参见 URL 中包含签名