OSSClient es el cliente de Android para el servicio OSS. Proporciona métodos para gestionar buckets y objetos. Antes de usar el kit de desarrollo de software (SDK) para enviar solicitudes a OSS, debe inicializar una instancia de OSSClient y establecer su configuración.
El ciclo de vida de OSSClient debe coincidir con el ciclo de vida de la aplicación. Cree un OSSClient global cuando inicie la aplicación y destruya OSSClient cuando la aplicación finalice.
Inicializar OSSClient
Un dispositivo móvil es un entorno no confiable. Almacenar directamente en el dispositivo los valores AccessKeyId y AccessKeySecret para firmar solicitudes representa un riesgo de seguridad alto. Se recomienda utilizar el modo de autenticación de Security Token Service (STS) o el modo autofirmado.
Incluso las credenciales temporales de STS se pueden extraer después de llegar al cliente móvil. Por lo tanto, debe restringirlas con una política de RAM que limite los permisos a un solo usuario y establezca un periodo de validez corto. En escenarios con datos sensibles como identificaciones oficiales, imágenes faciales o credenciales de pago, haga que el servidor de la aplicación genere una URL prefirmada para la aplicación móvil. De esta forma, la aplicación móvil nunca almacena una credencial. Para seleccionar el proveedor de credenciales, consulte Configure access credentials (Android SDK). Para obtener información sobre las URL prefirmadas, consulte Authorize access (Android SDK).
Puede crear un OSSClient de cualquiera de las siguientes maneras.
Para aprender a llamar a las interfaces de operaciones como cargas y descargas, consulte Quick Start (Android SDK).
El método de inicialización de OSSClient para listar buckets es distinto del método general que muestran estos ejemplos. Para más información, consulte List buckets (Android SDK).
Crear un OSSClient mediante STS
A continuación se muestra cómo crear un OSSClient mediante STS.
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
Crear un OSSClient con un nombre de dominio personalizado
A continuación se muestra cómo crear un OSSClient con un nombre de dominio personalizado.
// Set yourEndpoint to the custom domain name.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration config = new ClientConfiguration();
config.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
Crear un OSSClient en un entorno de Apsara Stack o de dominio privado
A continuación se muestra cómo crear un OSSClient en un entorno de Apsara Stack o de dominio privado.
// Set yourEndpoint to the Endpoint of the region where the bucket is located.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
ClientConfiguration configuration = new ClientConfiguration();
// Skip CNAME parsing.
List<String> excludeList = new ArrayList<>();
excludeList.add(endpoint);
configuration.setCustomCnameExcludeList(excludeList);
// Create an OSSClient instance.
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
Configurar OSSClient
ClientConfiguration es la clase de configuración de OSSClient. Con esta clase puede configurar parámetros como el proxy, el tiempo de espera de conexión y el número máximo de conexiones.
|
Parámetro |
Descripción |
Método |
|
maxConcurrentRequest |
Número máximo de solicitudes simultáneas. Valor predeterminado: 5. |
ClientConfiguration.setMaxConcurrentRequest |
|
socketTimeout |
Tiempo de espera para la transmisión de datos en la capa de socket, en milisegundos. Valor predeterminado: 60000. |
ClientConfiguration.setSocketTimeout |
|
connectionTimeout |
Tiempo de espera para establecer una conexión, en milisegundos. Valor predeterminado: 60000. |
ClientConfiguration.setConnectionTimeout |
|
max_log_size |
Tamaño del archivo de registro. Valor predeterminado: 5 MB. |
ClientConfiguration.setMaxLogSize |
|
maxErrorRetry |
Número máximo de reintentos tras un error en la solicitud. Valor predeterminado: 2. |
ClientConfiguration.setMaxErrorRetry |
|
customCnameExcludeList |
Los elementos de la lista omiten el análisis sintáctico de canonical name (CNAME). |
ClientConfiguration.setCustomCnameExcludeList |
|
proxyHost |
Dirección del host del servidor proxy. |
ClientConfiguration.setProxyHost |
|
proxyPort |
Puerto del servidor proxy. |
ClientConfiguration.setProxyPort |
|
mUserAgentMark |
Encabezado User-Agent de HTTP en el agente de usuario. |
ClientConfiguration.setUserAgentMark |
|
httpDnsEnable |
Indica si se habilita HTTPDNS.
|
ClientConfiguration.setHttpDnsEnable |
|
checkCRC64 |
Indica si se habilita la comprobación de redundancia cíclica de 64 bits (CRC-64). Valores válidos:
|
ClientConfiguration.setCheckCRC64 |
|
followRedirectsEnable |
Indica si se habilita la redirección HTTP. Valores válidos:
|
ClientConfiguration.setFollowRedirectsEnable |
|
okHttpClient |
Un okHttpClient personalizado. |
ClientConfiguration.setOkHttpClient |
A continuación se muestra cómo usar ClientConfiguration para establecer los parámetros de OSSClient.
// Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
String endpoint = "yourEndpoint";
// The temporary AccessKey ID and AccessKey secret obtained from the STS service.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// The security token obtained from the STS service.
String securityToken = "yourSecurityToken";
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
String region = "yourRegion";
ClientConfiguration configuration = new ClientConfiguration();
// Set the maximum number of concurrent requests. Default value: 5.
// configuration.setMaxConcurrentRequest(3);
// Set the timeout period for data transmission at the socket layer. Default value: 60s.
// configuration.setSocketTimeout(50000);
// Set the timeout period for establishing a connection. Default value: 60s.
// configuration.setConnectionTimeout(50000);
// Set the size of the log file. Default value: 5 MB.
// configuration.setMaxLogSize(3 * 1024 * 1024);
// Set the maximum number of retries after a request fails. Default value: 2.
// configuration.setMaxErrorRetry(3);
// Elements in the list will skip CNAME parsing.
// List<String> cnameExcludeList = new ArrayList<>();
// cnameExcludeList.add("cname");
// configuration.setCustomCnameExcludeList(cnameExcludeList);
// The host address of the proxy server.
// configuration.setProxyHost("yourProxyHost");
// The port of the proxy server.
// configuration.setProxyPort(8080);
// The User-Agent header of HTTP in the user agent.
// configuration.setUserAgentMark("yourUserAgent");
// Specifies whether to enable cyclic redundancy check (CRC). Default value: false.
// configuration.setCheckCRC64(true);
// Specifies whether to enable HTTP redirection. Default value: false.
// configuration.setFollowRedirectsEnable(true);
// Set a custom OkHttpClient.
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// configuration.setOkHttpClient(builder.build());
OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
configuration.setSignVersion(SignVersion.V4);
// Create an OSSClient instance.
OSSClient oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
oss.setRegion(region);
Habilitar el registro
El entorno de un dispositivo móvil es complejo. El SDK de OSS podría no funcionar correctamente en algunas regiones o durante ciertos periodos. Para ayudar a los desarrolladores a localizar problemas, el SDK de OSS guarda información de registro de forma local una vez que se habilita esta función. Para habilitar el registro, debe inicializarlo antes de usar OSSClient. Llame al método de la siguiente manera.
// Log style.
// Call OSSLog.enableLog() to enable viewing logs in the console.
// You can write log files to the \OSSLog\logs.csv path on the phone's built-in SD card. This is disabled by default.
// Logs record request data, response data, and exception information for OSS operations.
// For example, requestId and response header.
// The following is a sample log record.
// Android version.
// android_version: 5.1
// Android phone model.
// mobile_model: XT1085
// Network status.
// network_state: connected
// Network connection type.
// network_type: WIFI
// Specific operation behavior information.
// [2017-09-05 16:54:52] - Encounter local execpiton: //java.lang.IllegalArgumentException: The bucket name is invalid.
// A bucket name must:
// 1) be comprised of lower-case characters, numbers or dash(-);
// 2) start with lower case or numbers;
// 3) be between 3-63 characters long.
//------>end of log
// Call this method to enable logging.
OSSLog.enableLog();
Puede cargar los archivos a su servidor o utilizar Alibaba Cloud Simple Log Service para cargar los archivos de registro.
Interfaces síncronas y asíncronas
El SDK de Android proporciona ejemplos de llamadas síncronas y asíncronas para las interfaces de carga y descarga. Esto se debe a que el desarrollo de aplicaciones móviles no permite solicitudes de red en el hilo de la interfaz de usuario. Para las demás interfaces, los ejemplos principales son llamadas asíncronas.
-
Llamada síncrona
Una llamada a una interfaz síncrona bloquea el hilo hasta que devuelve un resultado.
No llame a interfaces síncronas desde el hilo de la interfaz de usuario.
Si ocurre una excepción durante una llamada a una interfaz síncrona, se lanza directamente una ClientException o una ServiceException. Una ClientException indica una excepción local, como un problema de conectividad de red o un parámetro no válido. Una ServiceException indica un error del servicio que devuelve OSS, como un fallo de autenticación o un error del servidor.
-
Llamada asíncrona
En una interfaz asíncrona, usted pasa una función de callback al hacer la solicitud. El resultado de la solicitud se procesa en dicho callback.
Si ocurre una excepción durante una solicitud asíncrona, la función de callback gestiona el error.
-
La llamada a una interfaz asíncrona devuelve directamente un Task.
OSSAsyncTask task = oss.asyncGetObejct(...); task.cancel(); // Cancel the task. task.waitUntilFinished(); // Wait until the task is complete. GetObjectResult result = task.getResult(); // Block the thread and wait for the result.