Cuando utilice el SDK de Object Storage Service (OSS) para C, debe inicializar las opciones de solicitud (oss_request_options_t) y especificar un endpoint.
Inicializar las opciones de solicitud
Usar el algoritmo de firma V4 (recomendado)
Se recomienda usar el algoritmo de firma V4 para mejorar la seguridad. Al inicializar el SDK con la firma V4, especifique un endpoint y un identificador de región de Alibaba Cloud. El identificador de región indica a qué región se envía la solicitud; por ejemplo, cn-hangzhou. También es obligatorio declarar signature_version = 4. Las firmas V4 son compatibles con el SDK de OSS para C a partir de la versión 3.11.0.
A continuación se muestra un ejemplo de código que crea una instancia de OSSClient mediante un endpoint de OSS y el algoritmo de firma V4. Si necesita crear la instancia de OSSClient con un nombre de dominio personalizado o con credenciales de acceso obtenidas de STS, modifique este código según corresponda.
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize the aos_string_t data type. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
// Specify two additional parameters.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether to use CNAME to access OSS. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters. The second parameter in this function specifies the ownership of ctl. By default, the value of the second parameter is 0. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main() {
aos_pool_t *p;
oss_request_options_t *options;
/* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
return -1;
}
/* Initialize the memory pool and options. */
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_options(options);
/* The logic code. In this example, the logic code is omitted. */
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */
aos_http_io_deinitialize();
return 0;
}
Usar el algoritmo de firma V1 (no recomendado)
A partir del 1 de marzo de 2025, Alibaba Cloud Object Storage Service (OSS) ya no ofrece la firma V1 a los usuarios nuevos (es decir, a los UID nuevos). Desde el 1 de septiembre de 2025, OSS dejará de actualizar y mantener la firma V1, y ya no la ofrecerá para los buckets de object storage nuevos. Cambie a la firma V4 lo antes posible para evitar interrupciones en el servicio. Para obtener más información, consulte Anuncio.
Usar un endpoint de OSS para inicializar las opciones de solicitud
El siguiente ejemplo de código muestra cómo inicializar las opciones de solicitud con un endpoint de OSS:
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize aos_string_t. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters. The second parameter in this function specifies the ownership of ctl. By default, the value of the second parameter is 0. */
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main() {
aos_pool_t *p;
oss_request_options_t *options;
/* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
return -1;
}
/* Initialize the memory pool and options. */
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_options(options);
/* The logic code. In this example, the logic code is omitted. */
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */
aos_http_io_deinitialize();
return 0;
}
Usar un nombre de dominio personalizado para inicializar las opciones de solicitud
El siguiente ejemplo de código muestra cómo inicializar las opciones de solicitud con un nombre de dominio personalizado:
#include "oss_api.h"
#include "aos_http_io.h"
# Specify the custom domain name. */
const char *endpoint = "yourCustomEndpoint";
void init_options(oss_request_options_t *options) {
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize aos_string_t. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* Enable CNAME and map the custom domain name to your bucket. */
options->config->is_cname = 1;
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main() {
aos_pool_t *p;
oss_request_options_t *options;
/* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
return -1;
}
/* Initialize the memory pool and options. */
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_options(options);
/* The logic code. In this example, the logic code is omitted. */
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */
aos_http_io_deinitialize();
return 0;
}
Usar credenciales de acceso temporales proporcionadas por STS para inicializar las opciones de solicitud
El siguiente ejemplo de código muestra cómo inicializar las opciones de solicitud con credenciales de acceso temporales obtenidas de Security Token Service (STS):
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Before you run the sample code, make sure that the YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET environment variables are configured to store temporary access credentials obtained from STS. */
const char *access_key_id = getenv("YOUR_ACCESS_KEY_ID");
const char *access_key_secret = getenv("YOUR_ACCESS_KEY_SECRET");
/* Specify the security token that is obtained from STS. */
const char *sts_token = "<yourSecurityToken>";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize aos_string_t. */
aos_str_set(&options->config->endpoint, endpoint);
aos_str_set(&options->config->access_key_id, access_key_id);
aos_str_set(&options->config->access_key_secret, access_key_secret);
/* Set the token. */
aos_str_set(&options->config->sts_token, sts_token);
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
options->ctl = aos_http_controller_create(options->pool, 0);
}
int main() {
aos_pool_t *p;
oss_request_options_t *options;
/* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
return -1;
}
/* Initialize the memory pool and options. */
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_options(options);
/* The logic code. In this example, the logic code is omitted. */
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */
aos_http_io_deinitialize();
return 0;
}
Parámetros
En la siguiente tabla se describen los parámetros comunes.
|
Parámetro |
Descripción |
|
speed_limit |
Límite inferior de la velocidad promedio. Unidad: bytes por segundo. Valor predeterminado: 1024. |
|
speed_time |
Duración mínima para calcular la velocidad promedio, en segundos. El valor predeterminado es 15. Importante
Los parámetros speed_limit y speed_time son obligatorios. La solicitud se interrumpe si la velocidad promedio permanece por debajo del límite inferior definido en speed_limit durante el tiempo indicado en speed_time. |
|
connect_timeout |
Tiempo de espera máximo para establecer una conexión. Unidad: segundos. Valor predeterminado: 10. |
|
dns_cache_timeout |
Tiempo de espera de la caché de DNS. Unidad: segundos. Valor predeterminado: 60. |
|
max_memory_size |
Tamaño máximo de datos que se pueden escribir en la memoria durante una descarga. Unidad: bytes. De forma predeterminada, el tamaño máximo de datos que se pueden escribir en la memoria durante una descarga es de 1 GB. |
|
enable_crc |
Indica si se habilita CRC-64. Valores válidos:
|
|
verify_ssl |
Indica si se habilita la autenticación basada en SSL. Valores válidos:
|
|
ca_path |
Ruta raíz del certificado de CA. Este parámetro es válido cuando verify_ssl se establece en 1. De forma predeterminada, este parámetro queda vacío. |
|
ca_file |
Ruta del certificado de CA. Este parámetro es válido cuando verify_ssl se establece en 1. De forma predeterminada, este parámetro queda vacío. |
|
proxy_host |
Dirección del servidor proxy con el formato |
|
proxy_auth |
Credenciales de autenticación del servidor proxy con el formato |
Ejemplos de configuración
Especificar un tiempo de espera
El siguiente ejemplo de código muestra cómo especificar un tiempo de espera:
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize aos_string_t. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters. The second parameter in this function specifies the ownership of ctl. By default, the value of the second parameter is 0. */
options->ctl = aos_http_controller_create(options->pool, 0);
/* Specify the timeout period for establishing a connection. Default value: 10. Unit: seconds. */
options->ctl->options->connect_timeout = 10;
/* Specify the timeout period of the DNS cache. Default value: 60. Unit: seconds. */
options->ctl->options->dns_cache_timeout = 60;
/*
Specify the timeout period.
Configure the speed_limit parameter to specify the lower limit on the average speed. Default value: 1024 (1 KB/s).
Configure the speed_time parameter to specify the allowed maximum time period for an average speed that is less than the lower speed limit. Default value: 15. Unit: seconds.
The following lines specify that a request timeout occurs when the transmission speed is less than 1 KB/s for 15 consecutive seconds:
*/
options->ctl->options->speed_limit = 1024;
options->ctl->options->speed_time = 15;
}
int main() {
aos_pool_t *p;
oss_request_options_t *options;
/* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
return -1;
}
/* Initialize the memory pool and options. */
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_options(options);
/* The logic code. In this example, the logic code is omitted. */
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */
aos_http_io_deinitialize();
return 0;
}
Configurar la autenticación basada en SSL
De forma predeterminada, la autenticación basada en SSL está habilitada en el SDK de OSS para C a partir de la versión 3.9.2. Si esta autenticación falla, compruebe que la ruta del certificado SSL sea correcta o deshabilite la autenticación basada en SSL.
El siguiente ejemplo de código muestra cómo configurar la autenticación basada en SSL:
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
void init_options(oss_request_options_t *options)
{
options->config = oss_config_create(options->pool);
/* Use a char* string to initialize aos_string_t. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
/* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
options->config->is_cname = 0;
/* Specify network parameters. The second parameter in this function specifies the ownership of ctl. By default, the value of the second parameter is 0. */
options->ctl = aos_http_controller_create(options->pool, 0);
/* Configure SSL-based authentication. */
Configure the verify_ssl parameter to specify whether to enable SSL-based authentication. Valid values: 0 and 1. Default value: 1. The value 1 specifies that SSL-based authentication is enabled.
Configure the ca_path parameter to specify the root path of the CA certificate. This parameter is valid when verify_ssl is set to 1. By default, this parameter is left empty.
Configure the ca_file parameter to specify the path of the CA certificate. This parameter is valid when verify_ssl is set to 1. By default, this parameter is left empty. */
/* Enable SSL-based authentication and specify the path of the CA certificate. */
//options->ctl->options->verify_ssl = 1;
//options->ctl->options->ca_path = "/etc/ssl/certs/";
//options->ctl->options->ca_file = "/etc/ssl/certs/ca-certificates.crt";
/* Disable SSL-based authentication. */
//options->ctl->options->verify_ssl = 0;
}
int main() {
aos_pool_t *p;
oss_request_options_t *options;
/* Initialize global variables. You need to initialize global variables only once in the program lifecycle. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
return -1;
}
/* Initialize the memory pool and options. */
aos_pool_create(&p, NULL);
options = oss_request_options_create(p);
init_options(options);
/* The logic code. In this example, the logic code is omitted. */
/* Release the memory pool. This operation releases the memory resources allocated for the request. */
aos_pool_destroy(p);
/* Release global resources that are allocated. You need to release global resources only once in the program lifecycle. */
aos_http_io_deinitialize();
return 0;
}