
# 创建桶
#### 操作场景
桶是OBS中存储对象的容器。您需要先创建一个桶，然后才能在OBS中存储数据。
下面介绍如何调用[创建桶](https://support.huaweicloud.com/api-obs/obs_04_0021.html)API在指定的区域创建一个桶，API的调用方法请参见[如何调用API](https://support.huaweicloud.com/api-obs/obs_04_0006.html)。
#### 前提条件
- 已获取AK和SK，获取方法参见[获取访问密钥（AK/SK）](https://support.huaweicloud.com/api-obs/obs_04_0116.html)。
- 您需要规划桶所在的区域信息，并根据区域确定调用API的Endpoint，详细信息请参见[地区和终端节点](https://developer.huaweicloud.com/endpoint?OBS)。
区域一旦确定，创建完成后无法修改。
#### 在cn-north-4区域创建一个名为bucket001的桶
示例中使用Apache HttpClient。
```
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 {
    /* 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险，建议在配置文件或者环境变量中密文存放，使用时解密，确保安全；
    本示例以ak和sk保存在环境变量中为例，运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。*/
    public static String accessKey = System.getenv("HUAWEICLOUD_SDK_AK"); //取值为获取的AK
    public static String securityKey = System.getenv("HUAWEICLOUD_SDK_SK");  //取值为获取的SK
    public static String region = "cn-north-4"; // 取值为规划桶所在的区域
    public static String createBucketTemplate =
            "<CreateBucketConfiguration " +
            "xmlns=\"http://obs.cn-north-4.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("https://bucket001.obs.cn-north-4.myhuaweicloud.com");
        httpPut.addHeader("Date", requesttime);
        httpPut.addHeader("Content-Type", contentType);
        /** 根据请求计算签名**/
        String contentMD5 = "";
        String canonicalizedHeaders = "";
        String canonicalizedResource = "/bucket001/";
        // Content-MD5 、Content-Type 没有直接换行， data格式为RFC 1123，和请求中的时间一致
        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);
            // 增加签名头域 Authorization: OBS AccessKeyID:signature
            httpPut.addHeader("Authorization", "OBS " + accessKey + ":" + signature);
            // 增加body体
            httpPut.setEntity(new StringEntity(createBucketTemplate));
            httpResponse = httpClient.execute(httpPut);
            // 打印发送请求信息和收到的响应消息
            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();
            }
        }
    }
}
```
**其中Date头域DateUtils的格式为：**
```
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);
    }
}
```
**签名字符串Signature的计算方法为：**
```
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;
    }
}
```
