Estos contenidos se han traducido de forma automática para su comodidad, pero Huawei Cloud no garantiza la exactitud de estos. Para consultar los contenidos originales, acceda a la versión en inglés.
Actualización más reciente 2023-07-11 GMT+08:00

Creación de un bucket

Casos

Un bucket es un contenedor que almacena objetos en OBS. Necesita crear un bucket antes de almacenar datos en OBS.

A continuación se describe cómo llamar a la API para crear un bucket en una región especificada. Para obtener más información sobre cómo llamar a una API, consulta Llamar a APIs.

Prerrequisitos

  • Usted ha obtenido el AK y el SK. Para obtener detalles sobre cómo obtener el AK y el SK, consulte Obtención de claves de acceso (AK/SK).
  • Ha planificado la región en la que desea crear un bucket y ha obtenido el endpoint necesario para las llamadas a la API. Para obtener más información, consulte Regiones y endpoint.

Una vez que se determina una región, no se puede modificar después de crear el bucket.

Creación de un bucket con nombre de bucket001 en la región a1

En este ejemplo, se utiliza un Apache HttpClient.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.obsclient;

import java.io.*;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class TestMain {

    public static String accessKey = "UDSIAMSTUBTEST000012"; //The value of this parameter is the AK obtained.
     public static String securityKey = "Udsiamstubtest000000UDSIAMSTUBTEST000012";  //The value of this parameter is the SK obtained.
    public static String region = "a1"; // The value is the region where the planned bucket resides.
    public static String createBucketTemplate =
            "<CreateBucketConfiguration " +
            "xmlns=\"http://obs.a1.myhuaweicloud.com/doc/2015-06-30/\">\n" +
            "<Location>" + region + "</Location>\n" +
            "</CreateBucketConfiguration>";

    public static void main(String[] str) {

         createBucket();

    }

    private static void createBucket() {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String requesttime = DateUtils.formatDate(System.currentTimeMillis());
        String contentType = "application/xml";
        
        HttpPut httpPut = new HttpPut("http://bucket001.obs.a1.myhuaweicloud.com");
        
        httpPut.addHeader("Date", requesttime);
        httpPut.addHeader("Content-Type", contentType);

        /**Calculate the signature based on the request.**/
        String contentMD5 = "";
        String canonicalizedHeaders = "";
        String canonicalizedResource = "/bucket001/";
        // Content-MD5 and Content-Type fields do not contain line breaks. The data format is RFC 1123, which is the same as the time in the request.
        String canonicalString = "PUT" + "\n" + contentMD5 + "\n" + contentType + "\n" + requesttime + "\n" + canonicalizedHeaders + canonicalizedResource;
        System.out.println("StringToSign:[" + canonicalString + "]");
        String signature = null;
        CloseableHttpResponse httpResponse = null;
        try {
            signature = Signature.signWithHmacSha1(securityKey, canonicalString);

             // Added the Authorization: OBS AccessKeyID:signature field to the header.
            httpPut.addHeader("Authorization", "OBS " + accessKey + ":" + signature);

            // Add a body.
            httpPut.setEntity(new StringEntity(createBucketTemplate));

            httpResponse = httpClient.execute(httpPut);

            // Prints the sending request information and the received response message.
            System.out.println("Request Message:");
            System.out.println(httpPut.getRequestLine());
            for (Header header : httpPut.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }

            System.out.println("Response Message:");
            System.out.println(httpResponse.getStatusLine());
            for (Header header : httpResponse.getAllHeaders()) {
                System.out.println(header.getName() + ":" + header.getValue());
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent()));

            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            reader.close();

            // print result
            System.out.println(response.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

El formato DateUtils del campo de encabezado Date es el siguiente:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package com.obsclient;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

public class DateUtils {

    public static String formatDate(long time)
    {
        DateFormat serverDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
        serverDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return serverDateFormat.format(time);
    }
}

El método para calcular string de caracteres de firma es el siguiente:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.obsclient;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.util.Base64;

public class Signature {
    public static String signWithHmacSha1(String sk, String canonicalString) throws UnsupportedEncodingException {

        try {
            SecretKeySpec signingKey = new SecretKeySpec(sk.getBytes("UTF-8"), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            return Base64.getEncoder().encodeToString(mac.doFinal(canonicalString.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}