UnityWebRequest發(fā)送圖片番宁、下載圖片委粉、json數(shù)據(jù)請求|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數(shù)據(jù)請求加密
    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字典數(shù)據(jù)
    /// </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參數(shù)不合法,缺少必須的示例:OperatorID,sig,TimeStamp,Seq,Data五個參數(shù)");
            }
            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
        {
            // 開辟一塊內(nèi)存流
            using (MemoryStream Memory = new MemoryStream())
            {
                // 把內(nèi)存流對象包裝成加密流對象
                using (CryptoStream Encryptor = new CryptoStream(Memory,
                Aes.CreateEncryptor(bKey, bVector),
                CryptoStreamMode.Write))
                {
                    // 明文數(shù)據(jù)寫入加密流
                    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
        {
            // 開辟一塊內(nèi)存流,存儲密文
            using (MemoryStream Memory = new MemoryStream(encryptedBytes))
            {
                // 把內(nèi)存流對象包裝成加密流對象
                using (CryptoStream Decryptor = new CryptoStream(Memory,
                Aes.CreateDecryptor(bKey, bVector),
                CryptoStreamMode.Read))
                {
                    // 明文存儲區(qū)
                    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);//轉(zhuǎn)化為jpg圖,可以壓縮20倍左右
        //form.AddBinaryData("file", imagebytes,  + ",file:" + fileName, "image/png");
        //添加文件(輸入對象的名字蓄愁、二進(jìn)制數(shù)組、文件對象類型)
        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-----
    /// 請求網(wǎng)絡(luò)圖片 根據(jù)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------
    /// 請求網(wǎng)絡(luò)圖片 根據(jù)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);
    }

//上傳圖片到服務(wù)器
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);//轉(zhuǎn)化為jpg圖,可以壓縮20倍左右
        //form.AddBinaryData("file", imagebytes,  + ",file:" + fileName, "image/png");
        //添加文件(輸入對象的名字狞悲、二進(jìn)制數(shù)組撮抓、文件對象類型)
        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
復(fù)制這段內(nèi)容后打開百度網(wǎng)盤手機App,操作更方便哦

LitJson.dll

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末摇锋,一起剝皮案震驚了整個濱河市丹拯,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌荸恕,老刑警劉巖乖酬,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異融求,居然都是意外死亡咬像,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門生宛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來县昂,“玉大人,你說我怎么就攤上這事陷舅〉拐茫” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵莱睁,是天一觀的道長待讳。 經(jīng)常有香客問我芒澜,道長,這世上最難降的妖魔是什么创淡? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任痴晦,我火速辦了婚禮,結(jié)果婚禮上辩昆,老公的妹妹穿的比我還像新娘阅酪。我一直安慰自己,他們只是感情好汁针,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布术辐。 她就那樣靜靜地躺著,像睡著了一般施无。 火紅的嫁衣襯著肌膚如雪辉词。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天猾骡,我揣著相機與錄音瑞躺,去河邊找鬼。 笑死兴想,一個胖子當(dāng)著我的面吹牛幢哨,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播嫂便,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼捞镰,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了毙替?” 一聲冷哼從身側(cè)響起岸售,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎厂画,沒想到半個月后凸丸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡袱院,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年屎慢,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片忽洛。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡抛人,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出脐瑰,到底是詐尸還是另有隱情妖枚,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布苍在,位于F島的核電站绝页,受9級特大地震影響荠商,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜续誉,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一莱没、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧酷鸦,春花似錦饰躲、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至摔握,卻和暖如春寄狼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背氨淌。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工泊愧, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人盛正。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓删咱,卻偏偏與公主長得像,于是被迫代替她去往敵國和親豪筝。 傳聞我的和親對象是個殘疾皇子腋腮,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容