OSS签名Header实现Demo(C#)

概述
OSS的集成上传和下载提供了SDK可以直接使用,但实际使用中一些用户受限环境或者设备限制需要使用api方式来实现上传和下载,本文以PutObject接口为例,提供了C#实现的demo。
注:建议优先使用OSS提供SDK,本文提供的只是签名实现上传demo,实际使用中需要结合业务来进行改动代码
详细信息
PutObject实现demo(visual studio 2017,NET Framework4.0)

using System;

using System.Security.Cryptography;

using System.Text;

using System.Net;

using System.IO;

using System.Reflection;



namespace Aliyun.OSS.Samples

{

    class Program

    {





        //您的AccessKey

        public static string AccessKey = "xx";

        //您的 AccessKeySecret

        public static string AccessKeySecret = "xx";

        //bucket所在的endpoint

        public static string Endpoint = "oss-cn-hangzhou.aliyuncs.com";

        public static string BucketName = "xx";

        public static string objectName = "mytest/1.txt";

        public static string HmacSha1Sign(string secret, string strOrgData)

        {

            var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(secret));

            var dataBuffer = Encoding.UTF8.GetBytes(strOrgData);

            var hashBytes = hmacsha1.ComputeHash(dataBuffer);

            return Convert.ToBase64String(hashBytes);

        }



        public static string HttpRequest(string url, string data, string sign, string contentType, string time1)

        {



            byte[] datas = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = "PUT";

            request.Timeout = 150000;

            request.Headers.Add("Authorization", "OSS " + AccessKey + ":" + sign);

            CallPrivateMethod(request, "SetSpecialHeaders", "Date", time1);

            request.ContentType = contentType;

            Stream requestStream = null;

            string responseStr = null;

            try

            {

                if (datas != null)

                {

                    request.ContentLength = datas.Length;

                    requestStream = request.GetRequestStream();

                    requestStream.Write(datas, 0, datas.Length);

                    requestStream.Close();

                }

                else

                {

                    request.ContentLength = 0;

                }

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                responseStr = response.Headers.GetValues("x-oss-request-id")[0];

                //responseStr = sr.ReadToEnd();

            }

            catch (Exception)

            {

                Console.WriteLine("error");

            }

            finally

            {

                request = null;

                requestStream = null;

            }

            return responseStr;

        }



        public static string ToGMTString()

        {

            return DateTime.Now.ToUniversalTime().ToString("r");

        }

        public static void CallPrivateMethod(object instance, string name, params object[] param)

        {

            BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;

            Type type = instance.GetType();

            MethodInfo method = type.GetMethod(name, flag);

            method.Invoke(instance, param);

        }



        static void Main(string[] args)

        {



            string varb = "PUT";

            string content_type = "application/json";

            string timeGmt = ToGMTString();

            string str = varb + "\n\n" + content_type + "\n" + timeGmt + "\n/" + BucketName + "/" + objectName;

            string signature = HmacSha1Sign(AccessKeySecret, str);

            string url = "http://" + BucketName + "." + Endpoint + "/" + objectName;

            string data = "{ \"key\":\"this is a oss's test\"}";

            string result = HttpRequest(url, data, signature, content_type, timeGmt);

            Console.WriteLine("requestId:  " + result);
        }

    }

}
上一篇:Eclipse自动生成作者、日期注释功能设置


下一篇:冬季实战营第一期:从零到一上手玩转云服务器学习报告