「转需」 Unity通过RestSharp调用阿里云OSS REST API

转载自 Shirlman 的 Unity通过RestSharp调用阿里云OSS REST API

Unity上用阿里云的oss服务,网上资料并不多,而且官方没有给出Unity的SDK,因此只能用REST API来实现了。
调研oss在unity上的可行性的话,开始总得跑个demo看看行不行的通,这里以上传图片为例子,可以先看看官方的文档
从文档中发现,需要自己实现签名,另外header中的信息和签名中的加密信息必须一致,比如时间和MD5值,如果签名算法有问题,阿里云就会返回相应的错误提示。
我自己封装了个简单的例子,有需要的可以参考下,在windows和android上测试通过,另外我用的是Unity5.4版本,RestSharp可以在文章最后下载,不知道什么版本,15年12月份的。
ps:为什么要用RestSharp?www不支持PUT,然后HttpWebRequest没试通,偷懒用RestSharp了,最近貌似都不更新了,但是用着感觉还行吧~
完整代码如下:

using UnityEngine;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using System;
using System.IO;
using RestSharp;

public class OssManager : MonoBehaviour {
    private const string OSS_HOST = "vrhouse.oss-cn-shanghai.aliyuncs.com";
    private const string BUCKET_NAME = "your_bucket_name";
    private const string ACCESS_KEY_ID = "your_access_key_id";
    private const string ACCESS_KEY_SECRET = "your_access_key_secret";

    private static OssManager mInstance;

    void Awake()
    {
        mInstance = this;
    }

    // Use this for initialization
    void Start () {

    }
    
    // Update is called once per frame
    void Update () {
    
    }

    public static OssManager GetInstance()
    {
        return mInstance;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="imagePath">本地文件绝对路径</param>
    /// <param name="bucketPath">需要保存的文件在bucket上的相对路径,前后不需要加'/',也不需要加文件名</param>
    public void UploadFileAsync(string imagePath, string bucketPath)
    {
        StartCoroutine(UploadImage(imagePath, bucketPath));
    }
    
    IEnumerator UploadImage(string imagePath, string bucketPath)
    {
        WWW loadedImage = new WWW("file:///" + imagePath);
        yield return loadedImage;

        string fileName = Path.GetFileName(imagePath);
        string bucketFilePath = "/" + bucketPath + "/" + fileName;
        string url = "http://" + OSS_HOST + bucketFilePath;
        string contentMD5 = ToMD5(imagePath);
        string contentType = "image/" + Path.GetExtension(imagePath).Remove(0, 1);
        string utcGMT = DateTime.UtcNow.ToString("r");
        string canonicalizedOSSHeaders = "";
        string canonicalizedResource = "/" + BUCKET_NAME + "/" + fileName;
        string authorization = GetAuthorization("PUT", contentMD5, contentType, utcGMT, canonicalizedOSSHeaders, canonicalizedResource);

        var client = new RestClient(url);
        var request = new RestRequest(Method.PUT);

        // Headers     
        request.AddHeader("Content-Encoding", "utf-8");
        request.AddHeader("Content-Md5", contentMD5);
        request.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
        request.AddHeader("Date", utcGMT);
        request.AddHeader("Content-Length", loadedImage.bytes.Length.ToString());
        request.AddHeader("Host", OSS_HOST);
        request.AddHeader("Authorization", "'" + authorization + "'"); // 这里一定要加引号

        // 这里需要这么处理,如果用AddFile,RestSharp会加multipart类型的content type,保存到OSS上的图片会无法查看
        request.AddParameter(contentType, loadedImage.bytes, ParameterType.RequestBody); 

        // execute the request
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string

        Debug.Log(content);
    }

    private string GetAuthorization(
        string method, string contentMD5, string contentType,
        string utcGMT, string canonicalizedOSSHeaders, string canonicalizedResource)
    {
        string data = method + "\n"
            + contentMD5 + "\n"
            + contentType + "\n"
            + utcGMT + "\n"
            + canonicalizedOSSHeaders
            + canonicalizedResource;

        string signature = ToHMACSHA1_Base64(ACCESS_KEY_SECRET, data);
        string authorization = "OSS " + ACCESS_KEY_ID + ":" + signature;

        return authorization;
    }

    private string ToHMACSHA1_Base64(string key, string data)
    {
        HMACSHA1 hmacsha1 = new HMACSHA1();
        hmacsha1.Key = Encoding.UTF8.GetBytes(key);
        byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
        byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
        string result = Convert.ToBase64String(hashBytes);

        return result;
    }

    private string ToMD5(string filePath)
    {
        FileStream file = new FileStream(filePath, FileMode.Open);
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] hashBytes = md5.ComputeHash(file);
        file.Close();
        string result = Convert.ToBase64String(hashBytes);

        return result;
    }
}

调用方式:

OssManager.GetInstance().UploadFileAsync("C:/Pictures/oss.jpg", "Images");

运行结果:

运行结果
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,947评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,349评论 25 708
  • 不知道从什么时候开始,夏天的变得如此燥热,离开了空调就像是一条被搁浅了曝晒在太阳下奄奄一息的大鱼。 突然很怀念,那...
    萤染阅读 557评论 2 7
  • 煞笔❗️
    ishshhs阅读 176评论 0 0
  • 人们常说,这世界上没有卖后悔药的。人们还说,我真是悔不当初啊。其实单从这两句话中就可以很清楚的知道,其实每个人都打...
    rcon阅读 320评论 0 0