Intégrez Alibaba Cloud Object Storage Service (OSS) à vos applications Java pour charger, télécharger et gérer des fichiers dans le cloud.
Intégration rapide
Suivez les étapes ci-dessous pour commencer à utiliser le SDK.
Prérequis
Java 8 ou version ultérieure.
Exécutez la commande java -version pour vérifier votre version de Java. Si Java n'est pas installé ou si la version est antérieure à Java 8, téléchargez et installez Java .
Installer le SDK
Ajoutez la dépendance du SDK via Maven ou compilez-le à partir du code source.
Maven
Ajoutez la dépendance suivante au fichier pom.xml. Remplacez <version> par la dernière version disponible dans le référentiel Maven.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-oss-v2</artifactId>
<version><!-- Specify the latest version number--></version>
</dependency>
Code source
Clonez le dépôt depuis Github et compilez-le avec Maven.
mvn clean install -DskipTests -Dgpg.skip=true
Configurer les identifiants d'accès
Définissez des variables d'environnement contenant la paire d'AccessKey d'un utilisateur RAM.
Dans la console RAM , créez un utilisateur RAM disposant d'un accès par Permanent AccessKey Pair . Conservez précieusement cette paire d'AccessKey, puis accordez l'autorisation AliyunOSSFullAccess à cet utilisateur.
Linux
-
Exécutez les commandes suivantes dans l'interface en ligne de commande pour ajouter la configuration des variables d'environnement au fichier
~/.bashrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc-
Exécutez la commande suivante pour appliquer les modifications.
source ~/.bashrc -
Exécutez les commandes suivantes pour vérifier que les variables d'environnement sont bien configurées.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
macOS
-
Exécutez la commande suivante dans le terminal pour identifier le shell par défaut.
echo $SHELL-
Suivez les étapes correspondant à votre shell par défaut.
Zsh
-
Exécutez les commandes suivantes pour ajouter la configuration des variables d'environnement au fichier
~/.zshrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Exécutez la commande suivante pour appliquer les modifications.
source ~/.zshrc -
Exécutez les commandes suivantes pour vérifier que les variables d'environnement sont bien configurées.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Exécutez les commandes suivantes pour ajouter la configuration des variables d'environnement au fichier
~/.bash_profile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Exécutez la commande suivante pour appliquer les modifications.
source ~/.bash_profile -
Exécutez les commandes suivantes pour vérifier que les variables d'environnement sont bien configurées.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
-
Windows
CMD
-
Exécutez les commandes suivantes dans l'invite de commandes.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"-
Exécutez les commandes suivantes pour vérifier que les variables d'environnement sont bien configurées.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
-
PowerShell
-
Exécutez les commandes suivantes dans 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)-
Exécutez les commandes suivantes pour vérifier que les variables d'environnement sont bien configurées.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Initialiser le client
Initialisez l'OSSClient en spécifiant une région.
L'OSSClient implémente l'interface AutoCloseable. Le bloc try-with-resources libère automatiquement les ressources sans appel explicite à close().
-
La création et la destruction d'un OSSClient consomment beaucoup de ressources. Adoptez le pattern singleton pour réutiliser une instance unique et appelez explicitement close() avant l'arrêt de l'application.
OSSClient synchrone
Utilisez le client synchrone lorsque vous devez attendre la fin de chaque opération avant de poursuivre.
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 asynchrone
Le client asynchrone permet d'exécuter plusieurs opérations OSS simultanément sans blocage.
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);
}
}
}
Exemple de sortie listant tous les buckets de votre compte :
bucket: name: examplebucket01, region: cn-hangzhou, storageClass: Standard
bucket: name: examplebucket02, region: cn-hangzhou, storageClass: Standard
Configurations du client
Utiliser un nom de domaine personnalisé
L'utilisation du nom de domaine OSS par défaut peut empêcher l'accès aux fichiers ou leur prévisualisation. Associez un nom de domaine personnalisé pour activer la prévisualisation dans le navigateur et l'accélération 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());
}
}
}
Contrôle des délais d'attente
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());
}
}
}
Politique de nouvelle tentative
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());
}
}
}
Protocole HTTP/HTTPS
Utilisez disableSsl(true) pour désactiver le protocole 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());
}
}
}
Utiliser un endpoint interne
Utilisez un endpoint interne pour accéder à OSS au sein de la même région afin de réduire les coûts de trafic et d'améliorer la vitesse.
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());
}
}
}
Utiliser un endpoint d'accélération des transferts
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());
}
}
}
Utiliser un domaine privé
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());
}
}
}
Utiliser un nom de domaine Gov Cloud
Configurez un OSSClient avec un nom de domaine 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());
}
}
}
Utiliser un HTTPClient personnalisé
Utilisez un client HTTP personnalisé lorsque les paramètres de configuration standard ne suffisent pas.
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());
}
}
}
Configuration des identifiants d'accès
Le SDK prend en charge plusieurs types d'identifiants. Sélectionnez la méthode adaptée à vos besoins d'authentification.
Comment choisir ses identifiants d'accès
Utiliser la paire d'AccessKey d'un utilisateur RAM
Initialisez le fournisseur d'identifiants avec la paire d'AccessKey (AccessKey ID et AccessKey secret) d'un compte Alibaba Cloud ou d'un utilisateur RAM. Cette méthode convient aux applications situées dans un environnement sécurisé qui nécessitent un accès OSS permanent. Elle exige toutefois une maintenance manuelle des clés, ce qui accroît les risques de sécurité.
Un compte Alibaba Cloud dispose de toutes les permissions sur ses ressources. La fuite de sa paire d'AccessKey représente un risque de sécurité majeur. Privilégiez plutôt un utilisateur RAM doté des permissions strictement nécessaires.
Pour créer une paire d'AccessKey pour un utilisateur RAM, consultez Créer une paire d'AccessKey. L'AccessKey ID et le secret ne s'affichent qu'au moment de la création. Sauvegardez-les immédiatement. En cas de perte, générez une nouvelle paire.
Configurer les variables d'environnement
Linux/macOS
-
Définissez les variables d'environnement à l'aide de la paire d'AccessKey de l'utilisateur RAM.
export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID' export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET' -
Exécutez les commandes suivantes pour vérifier que les variables d'environnement sont bien configurées.
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)
Exemple de code
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());
}
}
}
Configuration statique des identifiants
Codez en dur les identifiants d'accès en définissant explicitement la paire d'AccessKey.
N'intégrez jamais d'identifiants d'accès dans vos applications de production. Cette méthode est réservée aux tests.
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());
}
}
}
Utiliser un jeton STS
Utilisez les identifiants temporaires du Security Token Service (STS) — composés d'un AccessKey ID, d'un AccessKey secret et d'un jeton de sécurité — pour un accès OSS limité dans le temps. Vous devez renouveler manuellement le jeton avant son expiration.
Pour obtenir rapidement un jeton STS via OpenAPI, consultez AssumeRole - Obtenir des identifiants temporaires pour un rôle RAM.
Pour obtenir un jeton STS à l'aide d'un SDK, reportez-vous à Utiliser un jeton STS pour accéder à OSS.
Vous devez définir une date d'expiration lors de la génération d'un jeton STS. Le jeton devient invalide une fois ce délai écoulé.
Pour consulter la liste des endpoints du service STS, voir Endpoints de service.
Configurer les variables d'environnement
Cette méthode utilise des identifiants temporaires (AccessKey ID, AccessKey secret et jeton Security Token Service (STS)) obtenus auprès du STS, et non la paire d'AccessKey d'un utilisateur RAM.
L'AccessKey ID obtenu via le STS commence par « STS », par exemple « 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>
Exemple de code
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());
}
}
}
Configuration statique des identifiants
Codez en dur les identifiants temporaires en définissant explicitement la paire d'AccessKey et le jeton de sécurité.
N'intégrez jamais d'identifiants d'accès dans vos applications de production. Cette méthode est réservée aux tests.
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());
}
}
}
Utiliser les identifiants ARN de rôle RAM
Pour un accès inter-comptes, utilisez l'ARN d'un rôle RAM afin d'initialiser un fournisseur d'identifiants. Le SDK appelle automatiquement AssumeRole pour obtenir et renouveler les jetons STS. Vous pouvez également définir le paramètre policy pour restreindre davantage les permissions.
Un compte Alibaba Cloud dispose de toutes les permissions sur ses ressources. La fuite de sa paire d'AccessKey représente un risque de sécurité majeur. Privilégiez plutôt un utilisateur RAM doté des permissions strictement nécessaires.
Pour créer une paire d'AccessKey pour un utilisateur RAM, consultez Créer une paire d'AccessKey. L'AccessKey ID et le secret ne s'affichent qu'au moment de la création. Sauvegardez-les immédiatement. En cas de perte, générez une nouvelle paire.
Pour obtenir l'ARN d'un rôle RAM, reportez-vous à Créer un rôle RAM.
Ajouter une dépendance
Ajoutez la dépendance de gestion des identifiants Alibaba Cloud à votre fichier pom.xml.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>0.3.4</version>
</dependency>
Configurer une paire d'AccessKey et un ARN de rôle RAM comme identifiants d'accès
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());
}
}
}
Utiliser les identifiants de rôle RAM ECS
Pour les applications déployées sur des instances ECS, des instances ECI ou des nœuds worker Container Service for Kubernetes, utilisez un rôle RAM ECS. Le SDK récupère et renouvelle automatiquement les jetons STS temporaires, sans aucune gestion manuelle des clés. Pour configurer ce rôle, consultez Créer un rôle RAM.
Ajouter une dépendance
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>0.3.4</version>
</dependency>
Configurer un rôle RAM ECS comme identifiant d'accès
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());
}
}
}
Utiliser les identifiants ARN de rôle OIDC
Dans Container Service for Kubernetes, utilisez les RAM Roles for Service Accounts (RRSA) pour contrôler les permissions au niveau du pod. Le SDK utilise un jeton OIDC monté dans le pod pour assumer un rôle RAM et obtenir automatiquement des jetons STS temporaires. Utiliser RRSA pour accorder des permissions RAM à un ServiceAccount.
Ajouter une dépendance
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>credentials-java</artifactId>
<version>0.3.4</version>
</dependency>
Configurer un ARN de rôle OIDC comme identifiant d'accès
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());
}
}
}
Utiliser des identifiants d'accès personnalisés
Si les méthodes d'identification intégrées ne répondent pas à vos besoins, implémentez un fournisseur d'identifiants personnalisé.
Implémentation via l'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());
}
}
}
Implémentation de l'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());
}
}
}
Accès anonyme
Accédez aux ressources OSS en lecture publique sans fournir d'identifiants.
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());
}
}
}
Exemples de code
|
Classification des fonctionnalités |
Description de l'exemple |
Version synchrone |
Version asynchrone |
|
Bucket |
Créer un bucket |
||
|
Lister les buckets |
|||
|
Obtenir les informations d'un bucket |
|||
|
Obtenir la région d'un bucket |
|||
|
Obtenir les statistiques de stockage d'un bucket |
|||
|
Supprimer un bucket |
|||
|
Chargement de fichier |
Chargement simple |
||
|
Chargement par ajout |
|||
|
Chargement multipartite |
|||
|
Lister les tâches de chargement multipartite |
|||
|
Lister les parties chargées |
|||
|
Annuler un chargement multipartite |
|||
|
Téléchargement de fichier |
Téléchargement simple |
||
|
Gestion des fichiers |
Copier un fichier |
||
|
Vérifier l'existence d'un fichier |
|||
|
Lister les fichiers |
|||
|
Lister les fichiers V2 |
|||
|
Supprimer un fichier |
|||
|
Supprimer plusieurs fichiers |
|||
|
Obtenir les métadonnées d'un fichier |
|||
|
Objet archivé |
Restaurer un fichier |
||
|
Nettoyer un fichier restauré |
|||
|
Lien symbolique |
Créer un lien symbolique |
||
|
Obtenir un lien symbolique |
|||
|
Tagging d'objet |
Définir des tags d'objet |
||
|
Obtenir les tags d'un objet |
|||
|
Supprimer les tags d'un objet |
|||
|
Contrôle d'accès |
Définir l'ACL d'un bucket |
||
|
Obtenir l'ACL d'un bucket |
|||
|
Définir l'ACL d'un objet |
|||
|
Obtenir l'ACL d'un objet |
|||
|
Versioning |
Activer le versioning |
||
|
Obtenir l'état du versioning |
|||
|
Lister les versions d'un objet |
|||
|
Accès cross-domain |
Définir des règles CORS |
||
|
Obtenir les règles CORS |
|||
|
Supprimer les règles CORS |
|||
|
Requête preflight |
|||
|
Fonctionnalités système |
Interroger les informations d'endpoint |