UnityWebRequest发送图片、下载图片、json数据请求|HmacMD5加密解密

GetMessageFromServer

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using UnityEngine.Networking;
using LitJson;

public class GetMessageFromServer : MonoBehaviour {

    public static string LOCAL_OPERATORID = "123456789";
    
    public static string SERVER_OPERATOR_SECRET = "acb74125fc9bwe23";

    public static string SERVER_SIG_SECRET = "1q2we7b2d1478ad5";

    public static string SERVER_AES_SECRET = "1234qada0026123q";

    public static string SERVER_AES_IV = "12324qwe5e74basd1";


    public static String LOCAL_AES_SECRET = "1123asda0026cds1";

    public static String LOCAL_AES_IV = "12c123qwe44bef01";
    
    public static int SEQ = 1;

    public static string TEST_SERVER_URL = "http://xxxxxx.xxxxx.com/xxxx/20200701/";

    Dictionary<string, string> token_params = new Dictionary<string, string>();
    
    Dictionary<string, string> stationParams = new Dictionary<string, string>();

    string m_Token;
    
    void Start()
    {
        //获取token
        token_params.Add("OperatorID", LOCAL_OPERATORID);
        token_params.Add("OperatorSecret", SERVER_OPERATOR_SECRET);
        StartCoroutine(getResultFromDxpApi(token_params, "query_token", null));
       // StartCoroutine(MyPost());
        
        if (m_Token != null)
        {
            print(m_Token);
            // 获取信息
          //  StartCoroutine(getResultFromDxpApi(stationParams, "query_stations_info", m_Token));
        }
    }
    

    IEnumerator getResultFromDxpApi(Dictionary<string, string> token_params, string apiName, string token) {
        
        string queryUrl = TEST_SERVER_URL + apiName;
       
        string responseBody = "";

        UnityWebRequest request = new UnityWebRequest(queryUrl, "POST");

        //加密
        string requestEncode = RequestEncode(token_params);
        print(requestEncode);
        byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(requestEncode);
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        
        request.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
        if (token != null)
        {
            request.SetRequestHeader("Authorization", "Bearer " + token);
        }
        
        yield return request.Send();
      //  Debug.Log("Status Code: " + request.responseCode);
        //返回值
        responseBody = request.downloadHandler.text;
        Debug.Log(responseBody);
    }


    IEnumerator MyPost() {
        string requestEncode = RequestEncode(token_params);
        print(requestEncode);
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers.Add("Content-Type", "application/json;charset=UTF-8");
        WWW postData = new WWW(TEST_SERVER_URL, System.Text.Encoding.Default.GetBytes(requestEncode), headers);
        yield return postData;
        if (postData.error != null)
        {
            Debug.Log(postData.error);
        }
        else
        {
            Debug.Log(postData.text);
        }
    }


   

    string GetDictionaryValue(Dictionary<string, string> dic,string key) {
        string thisvalue;
        if (dic.TryGetValue(key, out thisvalue))
        {
            return thisvalue;
        }
        else {
            return null;
        }
    }


    // 获取Token数据请求加密
    public string RequestEncode(Dictionary<string, string> paramss)
    {
        string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
        try
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            string seq;
            seq = SEQ++.ToString().PadLeft(4, '0');

            string aesData = AesScript.instance.AESEncrypt(JsonConvert.SerializeObject(paramss), SERVER_AES_SECRET, SERVER_AES_IV);
              string signData = HmacMD5(SERVER_SIG_SECRET, LOCAL_OPERATORID + aesData + timestamp + seq).ToUpper();
            
           // result.Add("Sig", signData);
            result.Add("Data", aesData);
            result.Add("OperatorID", LOCAL_OPERATORID);
            result.Add("TimeStamp", timestamp);
            result.Add("Seq", seq);
            
            return JsonConvert.SerializeObject(result);
        }
        catch 
        {
           
        }
        return null;
    }
    
    public string HmacMD5(string key, string source)
    {
        HMACMD5 hmacmd = new HMACMD5(Encoding.UTF8.GetBytes(key));
        byte[] inArray = hmacmd.ComputeHash(Encoding.UTF8.GetBytes(source));
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < inArray.Length; i++)
        {
            sb.Append(inArray[i].ToString("X2"));
        }

        hmacmd.Clear();

        return sb.ToString();
    }

    
   
    /// <summary>
    /// 解密,返回解密后的Data字典数据
    /// </summary>
    /// <param name="responseBody"></param>
    /// <returns></returns>
    public Dictionary<string, string> responseDecode(string responseBody) {
        Dictionary<string, string> DecodeDataDic=null;
        try
        {
            Dictionary<string, string> DecodeDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseBody);

            if (DecodeDic == null)
            {
                throw new Exception("POST参数不合法,缺少必须的示例:OperatorID,sig,TimeStamp,Seq,Data五个参数");
            }
            string aesData;
            if (DecodeDic.TryGetValue("Data", out aesData))
            {
                // data反向aes解密
                string dataStr = AesScript.instance.AESDecrypt(aesData, SERVER_AES_SECRET, SERVER_AES_IV);
               // print(dataStr);
                DecodeDataDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(dataStr);
            }
           
        }
        catch (Exception)
        {
            throw;
        }
        return DecodeDataDic;
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System;
public class AesScript : MonoBehaviour {

    public static AesScript instance;

    private void Awake()
    {
        instance = this;
    }

    /// <summary>
    /// AES加密
    /// </summary>
    /// <param name="Data">被加密的明文</param>
    /// <param name="Key">密钥</param>
    /// <param name="Vector">向量</param>
    /// <returns>密文</returns>
    public string  AESEncrypt(string Data, string Key, string Vector)
    {
        Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);

        Byte[] bKey = new Byte[16];
        Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
        Byte[] bVector = new Byte[16];
        Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

        Byte[] Cryptograph = null; // 加密后的密文

        Rijndael Aes = Rijndael.Create();
        try
        {
            // 开辟一块内存流
            using (MemoryStream Memory = new MemoryStream())
            {
                // 把内存流对象包装成加密流对象
                using (CryptoStream Encryptor = new CryptoStream(Memory,
                Aes.CreateEncryptor(bKey, bVector),
                CryptoStreamMode.Write))
                {
                    // 明文数据写入加密流
                    Encryptor.Write(plainBytes, 0, plainBytes.Length);
                    Encryptor.FlushFinalBlock();

                    Cryptograph = Memory.ToArray();
                }
            }
        }
        catch
        {
            Cryptograph = null;
        }
        return Convert.ToBase64String(Cryptograph);
    }
    
    /// <summary>
    /// AES解密
    /// </summary>
    /// <param name="Data">被解密的密文</param>
    /// <param name="Key">密钥</param>
    /// <param name="Vector">向量</param>
    /// <returns>明文</returns>
    public  string AESDecrypt(string Data, string Key, string Vector)
    {
        Byte[] encryptedBytes = Convert.FromBase64String(Data);
        Byte[] bKey = new Byte[16];
        Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
        Byte[] bVector = new Byte[16];
        Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);

        Byte[] original = null; // 解密后的明文

        Rijndael Aes = Rijndael.Create();
        try
        {
            // 开辟一块内存流,存储密文
            using (MemoryStream Memory = new MemoryStream(encryptedBytes))
            {
                // 把内存流对象包装成加密流对象
                using (CryptoStream Decryptor = new CryptoStream(Memory,
                Aes.CreateDecryptor(bKey, bVector),
                CryptoStreamMode.Read))
                {
                    // 明文存储区
                    using (MemoryStream originalMemory = new MemoryStream())
                    {
                        Byte[] Buffer = new Byte[1024];
                        Int32 readBytes = 0;
                        while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
                        {
                            originalMemory.Write(Buffer, 0, readBytes);
                        }
                        original = originalMemory.ToArray();
                    }
                }
            }
        }
        catch (Exception e)
        {
            print(e);
            original = null;
        }
        return Encoding.UTF8.GetString(original);
    }
}

SendMessageToFlask

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class SendMessageToFlask : MonoBehaviour {

    public Texture2D texture;
    public RawImage rawImage;


    void Start () {

        //StartCoroutine(Get());
        StartCoroutine(ImagePost());
    }
    
    IEnumerator Get()
    {
       // string url = "http://192.168.6.2:5656/info/?name=zhang&age=18";
        string url = "http://8.129.176.192:5656/";

        UnityWebRequest webRequest = UnityWebRequest.Get(url);

        yield return webRequest.Send();
       
        if (webRequest.isError)
            Debug.Log(webRequest.error);
        else
        {
            Debug.Log(webRequest.downloadHandler.text);
        }
    }





    IEnumerator ImagePost()
    {
        string url = "http://192.168.6.2:5656/receive_image_bytes/";
        //string url = "http://192.168.6.2:5000/receive_image_bytes/";
        yield return new WaitForEndOfFrame();
        WWWForm form = new WWWForm();
        byte[] imagebytes = texture.EncodeToJPG(50);//转化为jpg图,可以压缩20倍左右
        //form.AddBinaryData("file", imagebytes,  + ",file:" + fileName, "image/png");
        //添加文件(输入对象的名字、二进制数组、文件对象类型)
        form.AddField("project", "flask01");  
        form.AddField("img_name", "flask01.jpg");
        form.AddBinaryData("file", imagebytes,"image/jpg");
        UnityWebRequest webRequest = UnityWebRequest.Post(url, form);
        yield return webRequest.Send();
        if (webRequest.isError)
            Debug.Log(webRequest.error);
        else
        {
             Debug.Log(webRequest.downloadHandler.text);
            StartCoroutine(LoadImageFromFlask(webRequest.downloadHandler.text));
            //StartCoroutine(PictureDownloding(webRequest.downloadHandler.text));
        }
    }


    /// <summary>
    /// -----UnityWebRequest-----
    /// 请求网络图片 根据URL下载图片 
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    IEnumerator LoadImageFromFlask(string url) {
        yield return new WaitForEndOfFrame();
        UnityWebRequest webRequest = new UnityWebRequest(url);
        DownloadHandlerTexture downloadTexture = new DownloadHandlerTexture(true);
        webRequest.downloadHandler = downloadTexture;
        yield return webRequest.Send();
        //int width = 300;
        //int high = 300;
        //Texture2D texture = new Texture2D(width, high);
        if (!(webRequest.isError))
        {
            //texture = downloadTexture.texture;
            rawImage.texture= downloadTexture.texture;
        }
    }
    

    /// <summary>
    /// -----WWW------
    /// 请求网络图片 根据URL下载图片 
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    IEnumerator PictureDownloding(string url)
    {
        WWW www = new WWW(url);
        while (www.isDone == false)
        {
            print("下载图片中" + www.progress);
            yield return null;
        }
        
        if (www.texture != null && string.IsNullOrEmpty(www.error))
        {
            string myjson = www.text;
            
            print("正在写入本地图片");
            byte[] pngData = www.texture.EncodeToPNG();
           string m_imagePath = Application.dataPath + "/Resources/NetPicture.jpg";
            File.WriteAllBytes(m_imagePath, pngData);
        }
    }
    
    IEnumerator Post()
    {
        WWWForm form = new WWWForm();
        //键值对
        form.AddField("key", "value");
        form.AddField("name", "mafanwei");
        form.AddField("blog", "qwe25878");

        UnityWebRequest webRequest = UnityWebRequest.Post("http://www.baidu.com", form);

        yield return webRequest.Send();
        
        if (webRequest.isError)
            Debug.Log(webRequest.error);
        else
        {
            Debug.Log(webRequest.downloadHandler.text);
        }
    }
}




IEnumerator UnityWebRequest_Post() {
        string queryUrl = "http://192.168.6.2:5656/webtest/getmsg_Post/";
        UnityWebRequest request = new UnityWebRequest(queryUrl, "POST");

        JsonData js = new JsonData();   //LitJson.dll
        js["msg1"] = "1";
        js["msg2"] = "2";
        print(js.ToJson());

       // string sss = "{\"msg1\":\"1\",\"msg2\":\"2\"}";
       // print(sss);
        byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(js.ToJson());
        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        request.SetRequestHeader("Authorization", "dXNlcm5hbWU6cGFzc3dvcmQKIA==");
        yield return request.Send();
        //  Debug.Log("Status Code: " + request.responseCode);
        //返回值
       string responseBody = request.downloadHandler.text;
        Debug.Log(responseBody);
    }

//上传图片到服务器
IEnumerator ImagePost()
    {
       // string url = "http://192.168.6.2:5656/receive_image_bytes/";
        string url = "http://39.108.165.190:5000/receive_image_bytes/";
        yield return new WaitForEndOfFrame();
        WWWForm form = new WWWForm();
        byte[] imagebytes = texture.EncodeToJPG(50);//转化为jpg图,可以压缩20倍左右
        //form.AddBinaryData("file", imagebytes,  + ",file:" + fileName, "image/png");
        //添加文件(输入对象的名字、二进制数组、文件对象类型)
        form.AddField("project", "flask01");  
        form.AddField("img_name", "flask01.jpg");
        form.AddBinaryData("file", imagebytes,"1.png");
        UnityWebRequest webRequest = UnityWebRequest.Post(url, form);
        yield return webRequest.Send();
        if (webRequest.isError)
            Debug.Log(webRequest.error);
        else
        {
             Debug.Log(webRequest.downloadHandler.text);
            StartCoroutine(LoadImageFromFlask(webRequest.downloadHandler.text));
            //StartCoroutine(PictureDownloding(webRequest.downloadHandler.text));
        }
    }

dll 下载

Newtonsoft.Json.dll

链接:https://pan.baidu.com/s/1XLXtUH0ks5jPsgoex_8VnA
提取码:b665
复制这段内容后打开百度网盘手机App,操作更方便哦

LitJson.dll

https://pan.baidu.com/s/1eeJn8H8EO7wRxqcK32J-Ug

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容