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

Posted vicf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了腾讯云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>

 

以上是关于腾讯云COS Api版本(不使用sdk)工具类的主要内容,如果未能解决你的问题,请参考以下文章

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

PHP 腾讯云cos使用之我见

腾讯云COS,上传,下载,删除,在线查看等操作

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

腾讯云对象存储使用

flutter 腾讯云 上传腾讯云cos 使用flutter1.12 1.17及以上版本 ios与flutter混合开发