概述
對象存儲OSS SDK提供了集成簽名、上傳和下載的SDK,但實際使用中,有時需要使用API的方式實現在簽名的情況下進行上傳和下載。本文以PutObject接口為例,為您提供C#語言實現的示例。
說明
建議優先使用OSS提供SDK,本文提供的只是簽名實現上傳示例,實際使用中需要結合業務進行代碼改動。
詳細信息
C#使用PutObject接口實現示例代碼如下。
說明
以下示例在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);
}
}
}
相關文檔
若您需要使用對象存儲OSS提供SDK,請參見OSS在Header中包含簽名。
適用于
對象存儲OSS
文檔內容是否對您有幫助?