OBS 使用API进行Put创建桶/上传对象

举报
yd_2755 发表于 2022/01/22 17:16:44 2022/01/22
【摘要】 本文将介绍如何使用Restful API接口,在obs进行put操作创建桶和上传对象一、创建桶首先 建立httpPut链接CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();RequestConfig defaultRequestConfig...

本文将介绍如何使用Restful API接口,在obs进行put操作创建桶和上传对象

一、创建桶

首先 建立httpPut链接

CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
HttpPut httpPut = new HttpPut("http://an-example-bucket.obs.cn-north-4.myhuaweicloud.com");

HttpPut中是发给obs的请求url, OBS根据桶和对象以及所对应的子资源参数来确定具体的URI,当需要进行资源操作时,可以使用这个URI地址。

URI的一般格式为(方括号内为可选项):

protocol://[bucket.]domain[:port][/object][?param]

URI中参数的具体含义如下:

参数

描述

是否必选

protocol

请求使用的协议类型,如HTTPHTTPsHTTPs表示通过安全的HTTPs访问该资源,对象存储服务支持HTTPHTTPs两种传输协议。

必选

bucket

请求使用的桶资源路径,在整个系统中唯一标识一个桶。

可选

domain

存放资源的服务器的域名或IP地址。

必选

port

请求使用的端口号。根据软件服务器的部署不同而不同。缺省时使用默认端口,各种传输协议都有默认的端口号,如HTTP的默认端口为80HTTPs的默认端口为443

可选

OBS对象存储服务的HTTP方式访问端口为80HTTPs方式访问端口为443

object

请求使用的对象资源路径。

可选

param

请求使用的桶和对象的具体资源,缺省默认为请求桶或对象自身资源。

可选

此示例中,在北京四region创建名为example1的桶

第二步,将必要的头域添加进入Put请求

String requesttime = formateDate(System.currentTimeMillis()); //获取当前请求发送时间
String contentType = "application/xml";

httpPut.addHeader("Date", requesttime);
httpPut.addHeader("Content-Type", contentType);
httpPut.addHeader("x-obs-acl", "public-read"); //设置桶的acl, 此处为公共读 可选择设置 若设置 需加入头域中

第三步,计算签名

obs请求中,签名计算非常重要,签名不匹配将导致请求失败

/** 根据请求计算签名**/
    String contentMD5 = "";
    String canonicalizedHeaders = "x-obs-acl:public-read";//设置的桶acl, 这个是可选的请求消息头 一般x-obs开头 
    String canonicalizedResource = "/an-example-bucket/"; //桶名
    // Content-MD5 、Content-Type 没有直接换行, data格式为RFC 1123,和请求中的时间一致
    String canonicalString = "PUT" + "\n" + contentMD5 + "\n" + contentType + "\n" + requesttime + "\n" + canonicalizedHeaders + "\n" + canonicalizedResource;

签名由HttpVerb(GET,PUT,HEAD等)+contentMD5+contentType+requesttime+canonicalizedHeaders+canonicalizedResources构成

其中canonicalizedHeaders是可选的请求消息头 一般以x-obs开头,比如:

注意 组成canonicalString时 以上签名元素之间必须加换行符

最后 计算签名

signature = signWithHmacSha1(securityKey, canonicalString);
// 增加签名头域 Authorization: OBS AccessKeyID:signature
httpPut.addHeader("Authorization", "OBS " + accessKey + ":" + signature);
// 增加body体
httpPut.setEntity(new StringEntity(createBucketTemplate));
httpPut.setConfig(defaultRequestConfig);
httpResponse = httpClient.execute(httpPut);

控制台上显示桶已创建:

返回200

完整创建桶代码示例:

public static String createBucketTemplate =
        "<CreateBucketConfiguration " +
                "xmlns=\"http://obs.cn-north-4.myhuaweicloud.com/doc/2015-06-30/\">\n" +
                "<Location>" + region + "</Location>\n" +
                "</CreateBucketConfiguration>";
private static void createBucket() {
    CredentialsProvider provider = new BasicCredentialsProvider();
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    RequestConfig defaultRequestConfig = RequestConfig.custom().build();


    String requesttime = formateDate(System.currentTimeMillis());
    String contentType = "application/xml";
    HttpPut httpPut = new HttpPut("http://example1.obs.cn-north-4.myhuaweicloud.com");


    httpPut.addHeader("Date", requesttime);
    httpPut.addHeader("Content-Type", contentType);
    httpPut.addHeader("x-obs-acl", "public-read");


    /** 根据请求计算签名**/
    String contentMD5 = "";
    String canonicalizedHeaders = "x-obs-acl:public-read";
    String canonicalizedResource = "/example1/";
    // Content-MD5 、Content-Type 没有直接换行, data格式为RFC 1123,和请求中的时间一致
    String canonicalString = "PUT" + "\n" + contentMD5 + "\n" + contentType + "\n" + requesttime + "\n" + canonicalizedHeaders + "\n" + canonicalizedResource;
    System.out.println("StringToSign:[" + canonicalString + "]");
    String signature = null;
    CloseableHttpResponse httpResponse = null;
    try {
        signature = signWithHmacSha1(securityKey, canonicalString);

        // 增加签名头域 Authorization: OBS AccessKeyID:signature
        httpPut.addHeader("Authorization", "OBS " + accessKey + ":" + signature);

        // 增加body体
        httpPut.setEntity(new StringEntity(createBucketTemplate));
        httpPut.setConfig(defaultRequestConfig);
        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();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
public static String signWithHmacSha1(String sk, String canonicalString) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        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 (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

二、使用put请求上传对象

put请求上传对象与创建桶类似, 但是需要在canonicalizedResource关键字填写好/bucketname/objectname 

url中需使用http://bucketname.obs.cn-north-4.myhuaweicloud.com/objectname格式

private static void putObjectToBucket() throws FileNotFoundException {
        CredentialsProvider provider = new BasicCredentialsProvider();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
        RequestConfig defaultRequestConfig = RequestConfig.custom().build();

        InputStream inputStream = null;

        CloseableHttpResponse httpResponse = null;
        String requesttime = formateDate(System.currentTimeMillis());
        HttpPut httpPut = new HttpPut("http://example1.obs.cn-north-4.myhuaweicloud.com/objecttest1");
        httpPut.addHeader("Date", requesttime);
        /** 根据请求计算签名 **/
        String contentMD5 = "";
        String contentType = "";
        String canonicalizedHeaders = "";
        String canonicalizedResource = "/example1/objecttest1"; //
        // Content-MD5 、Content-Type 没有直接换行, data格式为RFC 1123,和请求中的时间一致
        String canonicalString = "PUT" + "\n" + contentMD5 + "\n" + contentType + "\n" + requesttime + "\n" + canonicalizedHeaders + "\n" + canonicalizedResource;


        System.out.println("StringToSign:[" + canonicalString + "]");
        String signature = null;
        try {
            signature = signWithHmacSha1(securityKey, canonicalString);
            // 上传的文件目录

            inputStream = new FileInputStream("D:\\OBSobecjtTest\\third.txt");
            InputStreamEntity entity = new InputStreamEntity(inputStream);

            BufferedHttpEntity myEntity = null;
            try {
                myEntity = new BufferedHttpEntity(entity);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            httpPut.setEntity(myEntity);

            // 增加签名头域 Authorization: OBS AccessKeyID:signature
            httpPut.addHeader("Authorization", "OBS " + accessKey + ":" + signature);
            httpPut.setConfig(defaultRequestConfig);
            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 | NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。