腾讯云COS Api版本(不使用sdk)工具类

上一篇博文实现了阿里云OSS Api版本简单的上传和下载功能,这篇文章介绍腾讯云COS Api版本的上传下载功能

官方文档:https://cloud.tencent.com/document/product/436/7751

工具类代码:

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

public class CosWebApi {

    private static final String bucket = "test-12xxxxx";
    private static final String SecretId = "xxxxx";
    private static final String SecretKey = "xxxx";
    private static final String host = ".cos.ap-chengdu.myqcloud.com";//根据自己购买的产品替换

    //资源授权有效期(分钟)
    private static final int effectiveMinu = 10;

    public static final String LINE_SEPARATOR = "\n";
    public static final String Q_SIGN_ALGORITHM_KEY = "q-sign-algorithm";
    public static final String Q_SIGN_ALGORITHM_VALUE = "sha1";
    public static final String Q_AK = "q-ak";
    public static final String Q_SIGN_TIME = "q-sign-time";
    public static final String Q_KEY_TIME = "q-key-time";
    public static final String Q_HEADER_LIST = "q-header-list";
    public static final String Q_URL_PARAM_LIST = "q-url-param-list";
    public static final String Q_SIGNATURE = "q-signature";
    public static final String GET = "get";
    public static final String PUT = "put";

    public static String getGMTDate(){
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ‘GMT‘", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(cd.getTime());
    }

    public static String getAuthorization(Map<String, String> headers,Map<String, String> params,String httpMethod,
                                          String UriPathname) {

        Map<String, String> signHeaders = buildSignHeaders(headers);
        TreeMap<String, String> sortedSignHeaders = new TreeMap<>();
        TreeMap<String, String> sortedParams = new TreeMap<>();

        String qHeaderListStr = buildSignMemberStr(sortedSignHeaders);
        String qUrlParamListStr = buildSignMemberStr(sortedParams);

        sortedSignHeaders.putAll(signHeaders);
        sortedParams.putAll(params);
        String formatParameters = formatMapToStr(sortedParams);
        String formatHeaders = formatMapToStr(sortedSignHeaders);

        String formatStr = new StringBuilder().append(httpMethod).append(LINE_SEPARATOR)
                .append(UriPathname).append(LINE_SEPARATOR).append(formatParameters)
                .append(LINE_SEPARATOR).append(formatHeaders).append(LINE_SEPARATOR).toString();

        //增加
        Date expiredTime = new Date(System.currentTimeMillis() + effectiveMinu * 60 * 1000);
        String qKeyTimeStr, qSignTimeStr;
        qKeyTimeStr = qSignTimeStr = buildTimeStr(expiredTime);
        String hashFormatStr = DigestUtils.sha1Hex(formatStr);
        String stringToSign = new StringBuilder().append(Q_SIGN_ALGORITHM_VALUE)
                .append(LINE_SEPARATOR).append(qSignTimeStr).append(LINE_SEPARATOR)
                .append(hashFormatStr).append(LINE_SEPARATOR).toString();

        String signKey = HmacUtils.hmacSha1Hex(SecretKey, qKeyTimeStr);
        String signature = HmacUtils.hmacSha1Hex(signKey, stringToSign);

        String authoriationStr = new StringBuilder().append(Q_SIGN_ALGORITHM_KEY).append("=")
                .append(Q_SIGN_ALGORITHM_VALUE).append("&").append(Q_AK).append("=")
                .append(SecretId).append("&").append(Q_SIGN_TIME).append("=")
                .append(qSignTimeStr).append("&").append(Q_KEY_TIME).append("=").append(qKeyTimeStr)
                .append("&").append(Q_HEADER_LIST).append("=").append(qHeaderListStr).append("&")
                .append(Q_URL_PARAM_LIST).append("=").append(qUrlParamListStr).append("&")
                .append(Q_SIGNATURE).append("=").append(signature).toString();

        return authoriationStr;
    }

    //http get请求
    public static String get(String url,Map<String,String> head)throws IOException {
        HttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        for(String key : head.keySet()){
            httpGet.setHeader(key,head.get(key));
        }
        HttpResponse response = client.execute(httpGet);
        response.getEntity().getContent();
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity, "utf-8");
    }

    public static String buildTimeStr(Date expiredTime) {
        StringBuilder strBuilder = new StringBuilder();
        long startTime = System.currentTimeMillis() / 1000;
        long endTime = expiredTime.getTime() / 1000;
        strBuilder.append(startTime).append(";").append(endTime);
        return strBuilder.toString();
    }

    public static String formatMapToStr(Map<String, String> kVMap) {
        StringBuilder strBuilder = new StringBuilder();
        boolean seeOne = false;
        for (String key : kVMap.keySet()) {
            String lowerKey = key.toLowerCase();
            String encodeKey = encode(lowerKey);
            String encodedValue = "";
            if (kVMap.get(key) != null) {
                encodedValue = encode(kVMap.get(key));
            }
            if (!seeOne) {
                seeOne = true;
            } else {
                strBuilder.append("&");
            }
            strBuilder.append(encodeKey).append("=").append(encodedValue);
        }
        return strBuilder.toString();
    }

    private static Map<String, String> buildSignHeaders(Map<String, String> originHeaders) {
        Map<String, String> signHeaders = new HashMap<>();
        for (String key : originHeaders.keySet()) {

            if (key.equalsIgnoreCase("content-type") || key.equalsIgnoreCase("content-length")
                    || key.equalsIgnoreCase("content-md5") || key.startsWith("x")
                    || key.startsWith("X")) {
                String lowerKey = key.toLowerCase();
                String value = originHeaders.get(key);
                signHeaders.put(lowerKey, value);
            }
        }
        return signHeaders;
    }

    public static String buildSignMemberStr(Map<String, String> signHeaders) {
        StringBuilder strBuilder = new StringBuilder();
        boolean seenOne = false;
        for (String key : signHeaders.keySet()) {
            if (!seenOne) {
                seenOne = true;
            } else {
                strBuilder.append(";");
            }
            strBuilder.append(key.toLowerCase());
        }
        return strBuilder.toString();
    }

    public static String encode(String originUrl) {
        try {
            return URLEncoder.encode(originUrl, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
        } catch (UnsupportedEncodingException var2) {
            return null;
        }
    }

    public static String getObj(String key) {
        String gmtDate = getGMTDate();
        Map<String, String> headers = new HashMap<>();
        headers.put("Host",bucket + host);
        headers.put("Date",gmtDate);

        Map<String, String> params = new HashMap<>();
        String authorization = getAuthorization(headers, params, GET, key);

        Map<String, String> httpHeader = new HashMap<>();
        httpHeader.put("Host",bucket + host);
        httpHeader.put("Date",gmtDate);
        httpHeader.put("Authorization",authorization);

        try {
            return get("https://" + bucket + host + key, httpHeader);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    ////////////////////////////////////////////////////////////////////
    public static String shaEncode(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    public static String getSecondTimestamp(Date date){
        if (null == date) {
            return "";
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return timestamp.substring(0,length-3);
        } else {
            return "";
        }
    }
    public static String genHMAC(String key,String src) {
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("utf-8"), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(src.getBytes("utf-8"));
            return Hex.encodeHexString(rawHmac);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static void getUploadInformation(String  path,String obj) throws IOException, Exception {
        //创建连接
        URL url = new URL(path);
        HttpURLConnection connection ;
        StringBuffer sbuffer=null;
        try {
            //添加 请求内容
            connection= (HttpURLConnection) url.openConnection();
            //设置http连接属性
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("PUT");
            connection.setRequestProperty("Content-Length", obj.toString().getBytes().length + "");

            connection.setReadTimeout(10000);//设置读取超时时间
            connection.setConnectTimeout(10000);//设置连接超时时间
            connection.connect();
            OutputStream out = connection.getOutputStream();
            out.write(obj.toString().getBytes());
            out.flush();
            out.close();
            //读取响应
            if (connection.getResponseCode()==200)            {
                // 从服务器获得一个输入流
                InputStreamReader inputStream =new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(inputStream);

                String lines;
                sbuffer= new StringBuffer("");

                while ((lines = reader.readLine()) != null) {

                    lines = new String(lines.getBytes(), "utf-8");
                    sbuffer.append(lines);                }
                reader.close();
            }else{

            }
            //断开连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String putObj(String key,String content) {
        try {
            Date date_s = new Date();
            Date date_e = new Date();
            date_e.setTime(date_s.getTime() + effectiveMinu * 60 * 1000);

            String q_sign_algorithm = "sha1";
            String q_sign_time =getSecondTimestamp(date_s)+";"+getSecondTimestamp(date_e);
            String q_key_time = getSecondTimestamp(date_s)+";"+getSecondTimestamp(date_e);

            String SignKey = genHMAC(SecretKey, q_key_time);
            String HttpString = PUT + "\n" + key + "\n\n\n";
            String StringToSign = q_sign_algorithm + "\n" + q_sign_time + "\n" + shaEncode(HttpString) + "\n";
            String Signature = genHMAC(SignKey, StringToSign);

            String url = "https://" + bucket + host + key + "?q-sign-algorithm=" + q_sign_algorithm + "&q-ak=" + SecretId +
                    "&q-sign-time=" + q_sign_time + "&q-key-time=" + q_key_time + "&q-header-list=&q-url-param-list=&q-signature=" + Signature;

            getUploadInformation(url, content);
            return key;
        } catch (Exception ex) {
            System.out.println("上传失败:" + ex.getMessage());
            return null;
        }
    }

  //调用示例
    public static void main(String[] args) {

        String putResult = putObj("/test/2333333.txt", "test content");
        System.out.println("putResult:" + putResult);

        String getResult = getObj(putResult);
        System.out.println("getResult:" + getResult);
    }
}

引入jar包

<dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.13</version>
</dependency>

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
</dependency>

原文地址:https://www.cnblogs.com/vicF/p/11550003.html

时间: 2024-08-05 10:16:42

腾讯云COS Api版本(不使用sdk)工具类的相关文章

微信小程序/网站 上传图片到腾讯云COS

COS简介: 腾讯云提供的一种对象存储服务,供开发者存储海量文件的分布式存储服务.可以将自己开发的应用的存储部分全部接入COS的存储桶中,有效减少应用服务器的带宽,请求等.个人也可以通过腾讯云账号免费使用COS6个月,https://cloud.tencent.com/product/cos 整体流程简介:  1. 前端引入cos的SDK文件 2. 监听上传控件,并在图片加载至网页临时流中发起签名请求 3.后端根据上传的请求方式和路径参数返回签名Authorization和token XCosS

利用腾讯云COS云对象存储定时远程备份网站

版权声明:本文由张戈 原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/942851001487125915 来源:腾云阁 https://www.qcloud.com/community 一.优点分析 内网传输:和阿里云OSS一样,腾讯云COS同样支持内网和外网文件传输,对于腾讯云服务器,使用内网传输绝对是最快.最稳定的备份方案! 免费方案:看了下腾讯云COS的定价说明,发现对于备份网站来说简直是绝佳搭档,甚至可以说是钻

阿里云OSS和腾讯云COS互相迁移

利用阿里.腾讯的帮助文档中提供的迁移工具测试迁移对象存储数据. 一.腾讯to阿里文档链接:https://help.aliyun.com/document_detail/56990.html?spm=5176.7851628.6.1079.UqBdXKOssImport工具可以将本地.其它云存储的数据迁移到OSS,它有以下特点: 支持的丰富的数据源,有本地.七牛.百度BOS.AWS S3.Azure Blob.又拍云.腾讯云COS.金山KS3.HTTP.OSS等,并可根据需要扩展:支持断点续传:

腾讯云COS对象存储的简单使用

叮当哥之前买了一年的腾讯云服务器,昨日偶然发现腾讯云送了叮当哥半年的cos对象存储服务器,于是就撸起袖子传了几张珍藏的高清大图上去,现将其上传的简单使用步骤总结一波(其它操作参加官方SDK文档API). 说明:这里叮当哥使用的是生成临时密钥的方式(好处多多哦) 第一步:创建Maven工程并导入相关坐标 <!-- 1.添加腾讯云指定的仓库地址 --> <repositories> <repository> <id>bintray-qcloud-maven-re

PHP 腾讯云cos使用之我见

因为某些人的原因,本文从新改名发布一遍. 原名称:tp5 -- 腾讯云cos简单使用 原文链接:https://www.cnblogs.com/YFYQ/p/10840050.html 因项目需要,本来是需要对接阿里云oss,但因客户错误将云存储买成腾讯云cos,因此简单做了个对象上传使用 首先下载cos的sdk: 三种方式在文档上面都有介绍 SDK 安装有三种方式:Composer 方式.Phar 方式 和 源码方式. 本渣用的是最low 的源码方式 下载完成后解压放至TP5的第三方类库ext

腾讯云COS请求签名C#版

网上没有找到C#版 的签名代码,只好去一字一字的读SDK文档,自己写了一个,没有在CSDN搞什么积分下载,写的不好勿喷,能用点个赞再走. 空参和空的请求头是通过了与官方网的验证了,没有问题,可以直接下载COS中的文件.如果要带参,带头就自己试一下,如有有错告诉我一下再走. 文件名没有做过中文名的,我没有打算存中文的文件名,所以没有字符串特殊处理,用最简单的方式达到目的. using System; using System.Collections.Generic; using System.Co

腾讯云即时通信 IM 服务端 SDK for PHP

使用本扩展前需要登录 即时通信 IM 控制台 创建应用,配置管理员.获取 app_id.Key 等关键信息 更多请查看并熟读 即时通信 IM 服务端API , REST API 接口列表 一 腾讯云IM API(tp5通常放在extend目录下) <?phpnamespace tencentyun\im;/** 腾讯IM API*/class im{private $sdkappid; // 创建应用时即时通信 IM 控制台分配的 SDKAppIDprivate $identifier; //

[Baidu Map]百度地图 JAVASCRIPT API V2.0 大众版 工具类

关键代码: /* *@description 百度地图 JAVASCRIPT API V2.0 大众版 工具类 *@author YanZhiwei *@see http://developer.baidu.com/map/reference/index.php *@email [email protected] */ (function () { map = {}; infoWindow = {}; BmapUtils = { CONSTANT: { DYNAMIC_CITY: "上海&quo

关于调接口和腾讯云cos方面。

腾讯云的cos js jdk那个文档使用说明不好用. 都没看懂,而且图片上传也没有具体的详细.对于新手来说强制使用这个,弄得自己一头雾水. 工作效率就会下降. 为此我在网上搜了对象存储cos的常见错误. 对象存储COS常见问题大集结(2016年4月5日) 对象存储服务 PHp jquery基于cos上传头像组件 说真的全部都是php. 如果公司没有php,那用cos会出好多问题而且解决的时间成本太高. 为此我抱怨一下 作为前端我真的很不合格,如果没有后端,前端做这个腾讯cos什么都做不了.