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 token_params = new Dictionary();
    
    Dictionary stationParams = new Dictionary();

    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 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 headers = new Dictionary();
        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 dic,string key) {
        string thisvalue;
        if (dic.TryGetValue(key, out thisvalue))
        {
            return thisvalue;
        }
        else {
            return null;
        }
    }


    // 获取Token数据请求加密
    public string RequestEncode(Dictionary paramss)
    {
        string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
        try
        {
            Dictionary result = new Dictionary();
            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();
    }

    
   
    /// 
    /// 解密,返回解密后的Data字典数据
    /// 
    /// 
    /// 
    public Dictionary responseDecode(string responseBody) {
        Dictionary DecodeDataDic=null;
        try
        {
            Dictionary DecodeDic = JsonConvert.DeserializeObject>(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>(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;
    }

    /// 
    /// AES加密
    /// 
    /// 被加密的明文
    /// 密钥
    /// 向量
    /// 密文
    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);
    }
    
    /// 
    /// AES解密
    /// 
    /// 被解密的密文
    /// 密钥
    /// 向量
    /// 明文
    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));
        }
    }


    /// 
    /// -----UnityWebRequest-----
    /// 请求网络图片 根据URL下载图片 
    /// 
    /// 
    /// 
    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;
        }
    }
    

    /// 
    /// -----WWW------
    /// 请求网络图片 根据URL下载图片 
    /// 
    /// 
    /// 
    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

你可能感兴趣的:(UnityWebRequest发送图片、下载图片、json数据请求|HmacMD5加密解密)