Integre o Alibaba Cloud Object Storage Service (OSS) em aplicações Java para enviar, baixar e gerenciar arquivos na nuvem.
Integração rápida
Siga as etapas abaixo para começar a usar o SDK.
Pré-requisitos
Java 8 ou superior.
Execute o comando java -version para verificar sua versão do Java. Caso o Java não esteja instalado ou a versão seja anterior ao Java 8, baixe e instale o Java .
Instalar o SDK
Adicione a dependência do SDK via Maven ou compile a partir do código-fonte.
Maven
Adicione a seguinte dependência ao arquivo pom.xml. Substitua <version> pela versão mais recente disponível no Repositório Maven.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-oss-v2</artifactId>
<version><!-- Specify the latest version number--></version>
</dependency>
Código-fonte
Clone o repositório do Github e compile com o Maven.
mvn clean install -DskipTests -Dgpg.skip=true
Configurar credenciais de acesso
Defina variáveis de ambiente com o par de AccessKey de um usuário RAM.
No console do RAM , crie um usuário RAM com acesso de Permanent AccessKey Pair . Salve o par de AccessKey e conceda a permissão AliyunOSSFullAccess ao usuário.
Linux
-
Execute os comandos abaixo na interface de linha de comando para adicionar as definições de variáveis de ambiente ao arquivo
~/.bashrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Execute o comando a seguir para aplicar as alterações.
source ~/.bashrc -
Verifique se as variáveis de ambiente foram configuradas corretamente executando os comandos abaixo.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Execute o comando abaixo no terminal para identificar o tipo de shell padrão.
echo $SHELL-
Siga as instruções correspondentes ao seu tipo de shell padrão.
Zsh
-
Execute os comandos a seguir para anexar as configurações de variáveis de ambiente ao arquivo
~/.zshrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Execute o comando abaixo para aplicar as alterações.
source ~/.zshrc -
Verifique se as variáveis de ambiente estão configuradas executando os comandos seguintes.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Adicione as definições de variáveis de ambiente ao arquivo
~/.bash_profileusando os comandos abaixo.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Aplique as alterações com o comando a seguir.
source ~/.bash_profile -
Confirme a configuração das variáveis de ambiente executando estes comandos.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
No Prompt de Comando, execute os comandos abaixo.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Valide a configuração das variáveis de ambiente com os comandos a seguir.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Execute os comandos abaixo no PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)-
Para confirmar que as variáveis de ambiente foram definidas, execute:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Inicializar o cliente
Inicialize o OSSClient especificando uma região.
O OSSClient implementa AutoCloseable. Com try-with-resources, os recursos são liberados automaticamente sem necessidade de chamar close().
-
Criar e destruir instâncias do OSSClient consome muitos recursos. Utilize o padrão singleton para reutilizar uma única instância e chame close() explicitamente antes de encerrar a aplicação.
OSSClient síncrono
Utilize o cliente síncrono quando precisar aguardar a conclusão de cada operação antes de prosseguir.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.OSSClientBuilder;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
import com.aliyun.sdk.service.oss2.models.*;
import com.aliyun.sdk.service.oss2.paginator.ListBucketsIterable;
public class Example {
public static void main(String[] args) {
String region = "cn-hangzhou";
CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
OSSClientBuilder clientBuilder = OSSClient.newBuilder()
.credentialsProvider(provider)
.region(region);
try (OSSClient client = clientBuilder.build()) {
ListBucketsIterable paginator = client.listBucketsPaginator(
ListBucketsRequest.newBuilder()
.build());
for (ListBucketsResult result : paginator) {
for (BucketSummary info : result.buckets()) {
System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n", info.name(), info.region(), info.storageClass());
}
}
} catch (Exception e) {
// ServiceException se = ServiceException.asCause(e);
// if (se != null) {
// System.out.printf("ServiceException: requestId:%s, errorCode:%s\n", se.requestId(), se.errorCode());
// }
System.out.printf("error:\n%s", e);
}
}
}
OSSClient assíncrono
Use o cliente assíncrono para executar múltiplas operações no OSS simultaneamente, sem bloqueios.
import com.aliyun.sdk.service.oss2.OSSAsyncClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
import com.aliyun.sdk.service.oss2.models.*;
import java.util.concurrent.CompletableFuture;
public class ExampleAsync {
public static void main(String[] args) {
String region = "cn-hangzhou";
CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
try (OSSAsyncClient client = OSSAsyncClient.newBuilder()
.region(region)
.credentialsProvider(provider)
.build()) {
CompletableFuture<ListBucketsResult> future = client.listBucketsAsync(
ListBucketsRequest.newBuilder().build()
);
future.thenAccept(result -> {
for (BucketSummary info : result.buckets()) {
System.out.printf("bucket: name:%s, region:%s, storageClass:%s\n",
info.name(), info.region(), info.storageClass());
}
})
.exceptionally(e -> {
// ServiceException se = ServiceException.asCause(e);
// if (se != null) {
// System.out.printf("Async ServiceException: requestId:%s, errorCode:%s\n",
// se.requestId(), se.errorCode());
// }
System.out.printf("async error:\n%s\n", e);
return null;
});
future.join();
} catch (Exception e) {
System.out.printf("main error:\n%s\n", e);
}
}
}
Exemplo de saída listando todos os buckets da sua conta:
bucket: name: examplebucket01, region: cn-hangzhou, storageClass: Standard
bucket: name: examplebucket02, region: cn-hangzhou, storageClass: Standard
Configurações do cliente
Usar um nome de domínio personalizado
O uso do nome de domínio padrão do OSS pode impedir o acesso aos arquivos ou falhar na pré-visualização. Vincule um nome de domínio personalizado para habilitar a pré-visualização no navegador e a aceleração via CDN.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Specify your custom domain name. For example, www.example-***.com.
String endpoint = "https://www.example-***.com";
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
.endpoint(endpoint)
// Note: Set useCName to true to enable the CNAME option. Otherwise, you cannot use a custom domain name.
.useCName(true)
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Controle de tempo limite
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import java.time.Duration;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
// Set the timeout for establishing a connection. The default value is 5 seconds.
.connectTimeout(Duration.ofSeconds(30))
// Set the timeout for reading and writing data. The default value is 20 seconds.
.readWriteTimeout(Duration.ofSeconds(30))
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Política de nova tentativa
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import com.aliyun.sdk.service.oss2.retry.*;
import java.time.Duration;
public class Example {
public static void main(String[] args) {
/*
* SDK retry policy configuration description:
*
* Default retry policy:
* When no retry policy is configured, the SDK uses StandardRetryer as the default client implementation.
* Its default configuration is as follows:
* - maxAttempts: Sets the maximum number of attempts. The default is 3.
* - maxBackoff: Sets the maximum backoff time in seconds. The default is 20 seconds.
* - baseDelay: Sets the base delay time in seconds. The default is 0.2 seconds.
* - backoffDelayer: Sets the backoff algorithm. The default is the FullJitter backoff algorithm.
* Formula: [0.0, 1.0) * min(2^attempts * baseDelay, maxBackoff)
* - errorRetryables: Retryable error types, including HTTP status codes, service error codes, and client errors.
*
* When a retryable error occurs, the provided configuration is used to delay and then retry the request.
* The overall latency of the request increases with the number of retries. If the default configuration
* does not meet your scenario requirements, you can configure retry parameters or modify the retry implementation.
*/
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Retry policy configuration example:
// 1. Customize the maximum number of retries (default is 3, here set to 5).
Retryer customRetryer = StandardRetryer.newBuilder()
.maxAttempts(5)
.build();
// 2. Customize the backoff delay time.
// Adjust the baseDelay to 0.5 seconds (default 0.2 seconds) and maxBackoff to 25 seconds (default 20 seconds).
// Retryer customRetryer = StandardRetryer.newBuilder()
// .backoffDelayer(new FullJitterBackoff(Duration.ofMillis(500), Duration.ofSeconds(25)))
// .build();
// 3. Customize the backoff algorithm.
// Use a fixed-delay backoff algorithm instead of the default FullJitter algorithm, with a 2-second delay each time.
// Retryer customRetryer = StandardRetryer.newBuilder()
// .backoffDelayer(new FixedDelayBackoff(Duration.ofSeconds(2)))
// .build();
// 4. Disable the retry policy.
// To disable all retry attempts, use the NopRetryer implementation.
// Retryer customRetryer = new NopRetryer();
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
.retryer(customRetryer)
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Protocolo HTTP/HTTPS
Use disableSsl(true) para desativar o protocolo HTTPS.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
// Set to not use HTTPS requests.
.disableSsl(true)
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Usar um endpoint interno
Utilize um endpoint interno para acessar o OSS dentro da mesma região, reduzindo custos de tráfego e melhorando a velocidade.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Method 1: Specify the region and set useInternalEndpoint to true.
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// // Method 2: Directly specify the region and endpoint.
// // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
// String region = "cn-hangzhou";
// // Specify the internal endpoint for the bucket's region. For China (Hangzhou), the endpoint is 'oss-cn-hangzhou-internal.aliyuncs.com'.
// String endpoint = "oss-cn-hangzhou-internal.aliyuncs.com";
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
.useInternalEndpoint(true)
// .endpoint(endpoint) // If using Method 2, uncomment this line and comment out the previous one.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Usar um endpoint de aceleração de transferência
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Method 1: Specify the region and set useAccelerateEndpoint to true.
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// // Method 2: Directly specify the region and transfer acceleration endpoint.
// // Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
// String region = "cn-hangzhou";
// // Specify the transfer acceleration endpoint for the bucket's region, for example, 'https://oss-accelerate.aliyuncs.com'.
// String endpoint = "https://oss-accelerate.aliyuncs.com";
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
.useAccelerateEndpoint(true)
// .endpoint(endpoint) // If using Method 2, uncomment this line and comment out the previous one.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Usar um domínio privado
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Specify your private domain. For example: https://service.corp.example.com
String endpoint = "https://service.corp.example.com";
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
.endpoint(endpoint)
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Usar um nome de domínio Gov Cloud
Configure um OSSClient utilizando um nome de domínio do Alibaba Gov Cloud.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Specify the region and endpoint.
// Specify the region where the bucket is located. For China (Beijing) Gov Cloud 1, set the region to cn-north-2-gov-1.
String region = "cn-north-2-gov-1";
// Specify the internal endpoint for the bucket's region. For China (Beijing) Gov Cloud 1, the endpoint is 'https://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
// To specify the HTTP protocol, set the domain to 'http://oss-cn-north-2-gov-1-internal.aliyuncs.com'.
String endpoint = "https://oss-cn-north-2-gov-1-internal.aliyuncs.com";
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
.endpoint(endpoint)
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Usar um HTTPClient personalizado
Utilize um cliente HTTP personalizado quando os parâmetros de configuração padrão forem insuficientes.
import com.aliyun.sdk.service.oss2.*;
import com.aliyun.sdk.service.oss2.credentials.*;
import com.aliyun.sdk.service.oss2.transport.HttpClient;
import com.aliyun.sdk.service.oss2.transport.HttpClientOptions;
import com.aliyun.sdk.service.oss2.transport.apache5client.Apache5HttpClientBuilder;
import java.time.Duration;
public class Example {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Specify the region where the bucket is located. For example, for China (Hangzhou), set the region to cn-hangzhou.
String region = "cn-hangzhou";
// Set the parameters for the HTTP client.
HttpClientOptions httpClientOptions = HttpClientOptions.custom()
// Connection timeout. The default value is 5 seconds.
.connectTimeout(Duration.ofSeconds(30))
// Timeout for reading and writing data. The default value is 20 seconds.
.readWriteTimeout(Duration.ofSeconds(30))
// Maximum number of connections. The default value is 1024.
.maxConnections(2048)
// Specifies whether to skip certificate verification. By default, this is false.
.insecureSkipVerify(false)
// Specifies whether to enable HTTP redirection. By default, this is disabled.
.redirectsEnabled(false)
// Set the proxy server.
// .proxyHost("http://user:passswd@proxy.example-***.com")
.build();
// Create an HTTP client and pass in the HTTP client parameters.
HttpClient httpClient = Apache5HttpClientBuilder.create()
.options(httpClientOptions)
.build();
// Create an OSS client with the configured information.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region(region)
.httpClient(httpClient)
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}
Configurações de credenciais de acesso
O SDK suporta diversos tipos de credenciais. Escolha o método mais adequado às suas necessidades de autenticação.
Como escolher credenciais de acesso
Usar o par de AccessKey de um usuário RAM
Inicialize o provedor de credenciais com o par de AccessKey (AccessKey ID e AccessKey secret) de uma conta Alibaba Cloud ou de um usuário RAM. Ideal para aplicações em ambientes seguros que necessitam de acesso prolongado ao OSS. Essa abordagem exige manutenção manual das chaves, o que aumenta o risco de segurança.
Uma conta Alibaba Cloud possui permissões totais sobre seus recursos. O vazamento do seu par de AccessKey representa um risco significativo de segurança. Prefira utilizar um usuário RAM com as permissões mínimas necessárias.
Para criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey. O AccessKey ID e o segredo são exibidos apenas no momento da criação. Salve-os imediatamente. Se perdê-los, crie um novo par.
Configurar variáveis de ambiente
Linux/macOS
-
Defina as variáveis de ambiente utilizando o par de AccessKey do usuário RAM.
export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID' export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET' -
Execute os comandos a seguir para validar a configuração das variáveis de ambiente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
PowerShell
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Exemplo de código
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
public class OSSExample {
public static void main(String[] args) {
// Load credential information from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Create an OSS client.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Configuração estática de credenciais
Codifique as credenciais de acesso diretamente definindo explicitamente o par de AccessKey.
Não incorpore credenciais de acesso nas suas aplicações de produção. Este método destina-se apenas a testes.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider;
public class OSSExample {
public static void main(String[] args) {
// Create a static credential provider and explicitly set the AccessKey pair.
// Replace with your RAM user's AccessKey ID and AccessKey secret.
CredentialsProvider credentialsProvider = new StaticCredentialsProvider(
"YOUR_ACCESS_KEY_ID",
"YOUR_ACCESS_KEY_SECRET"
);
// Create an OSS client.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Usar um token STS
Utilize credenciais temporárias do Security Token Service (STS) — compostas por AccessKey ID, AccessKey secret e um token de segurança — para acesso ao OSS com tempo limitado. É necessário renovar manualmente o token antes que ele expire.
Para obter rapidamente um token STS via OpenAPI, consulte AssumeRole - Obter credenciais de identidade temporárias para uma função RAM.
Para obter um token STS usando um SDK, veja Usar um token STS para acessar o OSS.
É obrigatório definir um tempo de expiração ao gerar um token STS. O token torna-se inválido após esse período.
Para consultar a lista de endpoints do serviço STS, acesse Endpoints de serviço.
Configurar variáveis de ambiente
Este método utiliza credenciais de identidade temporárias (AccessKey ID, AccessKey secret e um token do Security Token Service - STS) obtidas via STS, e não o par de AccessKey de um usuário RAM.
O AccessKey ID obtido do STS começa com "STS", por exemplo, "STS.L4aBSCSJVMuKg5U1****".
Linux/macOS
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
Windows
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
Exemplo de código
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
public class OSSExample {
public static void main(String[] args) {
// Load the authentication information required to access OSS from environment variables for identity verification.
CredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();
// Create an OSS client.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Configuração estática de credenciais
Codifique as credenciais temporárias definindo explicitamente o par de AccessKey e o token de segurança.
Evite incorporar credenciais de acesso em aplicações de produção. Utilize este método exclusivamente para fins de teste.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider;
public class OSSExample {
public static void main(String[] args) {
// Specify the obtained temporary AccessKey ID and AccessKey secret.
// Note that the AccessKey ID obtained from STS starts with "STS".
String stsAccessKeyId = "STS.****************";
String stsAccessKeySecret = "yourAccessKeySecret";
String stsSecurityToken = "yourSecurityToken";
// Create a static credential provider and explicitly set the temporary AccessKey pair and STS security token.
CredentialsProvider credentialsProvider = new StaticCredentialsProvider(
stsAccessKeyId,
stsAccessKeySecret,
stsSecurityToken
);
// Create an OSS client.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Usar credenciais de ARN de função RAM
Para acesso entre contas, utilize o ARN de uma função RAM para inicializar um provedor de credenciais. O SDK chama automaticamente o AssumeRole para obter e renovar tokens STS. Defina o parâmetro policy para restringir ainda mais as permissões.
Uma conta Alibaba Cloud tem controle total sobre seus recursos. O vazamento do par de AccessKey gera alto risco de segurança. Recomenda-se o uso de um usuário RAM com permissões mínimas.
Para gerar um par de AccessKey para um usuário RAM, veja Criar um par de AccessKey. Lembre-se de salvar o AccessKey ID e o segredo imediatamente após a criação, pois eles não serão exibidos novamente. Em caso de perda, crie um novo par.
Para obter o ARN de uma função RAM, consulte Criar uma função RAM.
Adicionar uma dependência
Inclua a dependência de gerenciamento de credenciais do Alibaba Cloud no seu arquivo pom.xml.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>0.3.4</version>
</dependency>
Configurar um par de AccessKey e ARN de função RAM como credenciais de acesso
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;
public class OSSExample {
public static void main(String[] args) {
// Configure RAM role ARN credentials.
Config credentialConfig = new Config()
.setType("ram_role_arn")
// Obtain the RAM user's AccessKey pair (AccessKey ID and AccessKey secret) from environment variables.
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
// The ARN of the RAM role to assume. Example value: acs:ram::123456789012****:role/adminrole
// You can set the RoleArn via the ALIBABA_CLOUD_ROLE_ARN environment variable.
.setRoleArn("acs:ram::123456789012****:role/adminrole")
// The role session name. You can set the RoleSessionName via the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
.setRoleSessionName("your-session-name")
// Set a more restrictive permission policy. This is optional. Example value: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
.setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}")
// Set the role session validity period in seconds. The default is 3600 seconds (1 hour). This is optional.
.setRoleSessionExpiration(3600);
Client credentialClient = new Client(credentialConfig);
// Create a credential provider for dynamic credential loading.
CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
try {
com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
return new Credentials(
cred.getAccessKeyId(),
cred.getAccessKeySecret(),
cred.getSecurityToken()
);
} catch (Exception e) {
throw new RuntimeException("Failed to obtain credentials", e);
}
});
// Create an OSS client instance.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located, for example, China (Hangzhou).
.build()) {
// Use the client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Usar credenciais de função RAM do ECS
Para aplicações em instâncias ECS, instâncias ECI ou nós de trabalho do Container Service for Kubernetes, utilize uma função RAM do ECS. O SDK recupera e renova automaticamente os tokens STS temporários, eliminando a necessidade de gerenciamento manual de chaves. Para configurar a função, consulte Criar uma função RAM.
Adicionar uma dependência
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>0.3.4</version>
</dependency>
Configurar uma função RAM do ECS como credencial de acesso
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;
public class OSSExample {
public static void main(String[] args) {
// Configure ECS RAM role credentials.
Config credentialConfig = new Config()
.setType("ecs_ram_role") // Access credential type. Fixed as ecs_ram_role.
.setRoleName("EcsRoleExample"); // The name of the RAM role granted to the ECS instance. Optional parameter. If not set, it will be automatically retrieved. We strongly recommend setting it to reduce requests.
Client credentialClient = new Client(credentialConfig);
// Create a credential provider for dynamic credential loading.
CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
try {
com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
return new Credentials(
cred.getAccessKeyId(),
cred.getAccessKeySecret(),
cred.getSecurityToken()
);
} catch (Exception e) {
throw new RuntimeException("Failed to obtain credentials", e);
}
});
// Create an OSS client instance.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located, for example, China (Hangzhou).
.build()) {
// Use the client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Usar credenciais de ARN de função OIDC
No Container Service for Kubernetes, utilize RAM Roles for Service Accounts (RRSA) para controle de permissões no nível de pod. O SDK usa um token OIDC montado no pod para assumir uma função RAM e obter automaticamente tokens STS temporários. Consulte Usar RRSA para conceder permissões RAM a uma ServiceAccount.
Adicionar uma dependência
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>0.3.4</version>
</dependency>
Configurar um ARN de função OIDC como credencial de acesso
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
// Note: The following imports are from the external dependency credentials-java
import com.aliyun.credentials.Client;
import com.aliyun.credentials.models.Config;
public class OSSExample {
public static void main(String[] args) {
// Configure OIDC role ARN credentials.
Config credentialConfig = new Config()
// Specify the credential type. Fixed as oidc_role_arn.
.setType("oidc_role_arn")
// The RAM role ARN. You can set the RoleArn via the ALIBABA_CLOUD_ROLE_ARN environment variable.
.setRoleArn(System.getenv("ALIBABA_CLOUD_ROLE_ARN"))
// The OIDC provider ARN. You can set the OidcProviderArn via the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
.setOidcProviderArn(System.getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN"))
// The OIDC token file path. You can set the OidcTokenFilePath via the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
.setOidcTokenFilePath(System.getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE"))
// The role session name. You can set the RoleSessionName via the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
.setRoleSessionName("your-session-name")
// Set a more restrictive permission policy. This is optional. Example value: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
.setPolicy("{\"Statement\": [{\"Action\": [\"*\"],\"Effect\": \"Allow\",\"Resource\": [\"*\"]}],\"Version\":\"1\"}")
// Set the role session validity period in seconds. The default is 3600 seconds (1 hour). This is optional.
.setRoleSessionExpiration(3600);
Client credentialClient = new Client(credentialConfig);
// Create a credential provider for dynamic credential loading.
CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
try {
com.aliyun.credentials.models.CredentialModel cred = credentialClient.getCredential();
return new Credentials(
cred.getAccessKeyId(),
cred.getAccessKeySecret(),
cred.getSecurityToken()
);
} catch (Exception e) {
throw new RuntimeException("Failed to obtain credentials", e);
}
});
// Create an OSS client instance.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located, for example, China (Hangzhou).
.build()) {
// Use the client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Usar credenciais de acesso personalizadas
Caso os métodos nativos de credenciais não atendam às suas necessidades, implemente um provedor de credenciais personalizado.
Implementar através da interface Supplier
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProviderSupplier;
public class OSSExample {
public static void main(String[] args) {
// Create a custom credential provider.
CredentialsProvider credentialsProvider = new CredentialsProviderSupplier(() -> {
// TODO: Implement your custom credential retrieval logic.
// Return long-term credentials.
return new Credentials("access_key_id", "access_key_secret");
// Return an STS token (if needed).
// return new Credentials("sts_access_key_id", "sts_access_key_secret", "security_token");
});
// Create an OSS client.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Implementar a interface CredentialsProvider
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
public class CustomCredentialsProvider implements CredentialsProvider {
@Override
public Credentials getCredentials() {
// TODO: Implement your custom credential retrieval logic.
// Return long-term credentials.
return new Credentials("access_key_id", "access_key_secret");
// Return an STS token (if needed).
// For temporary credentials, you need to refresh them based on their expiration time.
// return new Credentials("sts_access_key_id", "sts_access_key_secret", "security_token");
}
}
public class OSSExample {
public static void main(String[] args) {
// Create a custom credential provider.
CredentialsProvider credentialsProvider = new CustomCredentialsProvider();
// Create an OSS client.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located.
.build()) {
// Use the created client for subsequent operations...
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Acesso anônimo
Acesse recursos OSS com permissão de leitura pública sem fornecer credenciais.
import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.AnonymousCredentialsProvider;
public class OSSExample {
public static void main(String[] args) {
// Create an anonymous credential provider.
CredentialsProvider credentialsProvider = new AnonymousCredentialsProvider();
// Create an OSS client.
try (OSSClient client = OSSClient.newBuilder()
.credentialsProvider(credentialsProvider)
.region("cn-hangzhou") // Specify the region where the bucket is located.
.build()) {
// Use the created client for subsequent operations...
// Note: Anonymous access can only be used for resources with public-read permissions.
} catch (Exception e) {
System.err.println("Operation failed: " + e.getMessage());
}
}
}
Códigos de exemplo
|
Classificação do recurso |
Descrição do exemplo |
Versão síncrona |
Versão assíncrona |
|
Bucket |
Criar um bucket |
||
|
Listar buckets |
|||
|
Obter informações do bucket |
|||
|
Obter região do bucket |
|||
|
Obter estatísticas de armazenamento do bucket |
|||
|
Excluir um bucket |
|||
|
Upload de arquivo |
Upload simples |
||
|
Upload por anexação |
|||
|
Upload multipart |
|||
|
Listar tarefas de upload multipart |
|||
|
Listar partes carregadas |
|||
|
Cancelar um upload multipart |
|||
|
Download de arquivo |
Download simples |
||
|
Gerenciamento de arquivos |
Copiar um arquivo |
||
|
Verificar se um arquivo existe |
|||
|
Listar arquivos |
|||
|
Listar arquivos V2 |
|||
|
Excluir um arquivo |
|||
|
Excluir vários arquivos |
|||
|
Obter metadados do arquivo |
|||
|
Objeto arquivado |
Restaurar um arquivo |
||
|
Limpar um arquivo restaurado |
|||
|
Link simbólico |
Criar um link simbólico |
||
|
Obter um link simbólico |
|||
|
Tags de objeto |
Definir tags de objeto |
||
|
Obter tags de objeto |
|||
|
Excluir tags de objeto |
|||
|
Controle de acesso |
Definir ACL do bucket |
||
|
Obter ACL do bucket |
|||
|
Definir ACL do objeto |
|||
|
Obter ACL do objeto |
|||
|
Versionamento |
Definir versionamento |
||
|
Obter status do versionamento |
|||
|
Listar versões de objetos |
|||
|
Acesso entre domínios |
Definir regras CORS |
||
|
Obter regras CORS |
|||
|
Excluir regras CORS |
|||
|
Requisição preflight |
|||
|
Recursos do sistema |
Consultar informações de endpoint |