Unity HTTP数据Get、Post

Get:

 /// 
    /// Get请求
    /// 
    /// 请求地址
    /// 接口回调
    public void Get(string url, Action callback)
    {
        StartCoroutine(I_RequestGET(url, callback));
    }

    /// 
    /// 接口请求携程
    /// 
    private static IEnumerator I_RequestGET(string url, Action callback)
    {
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.certificateHandler = new WebRequestCertificate();
        yield return request.SendWebRequest();
        Debug.Log(request.error);
        Debug.Log(request.responseCode);
        Debug.Log(request.downloadHandler.text);
        callback?.Invoke(request.downloadHandler.text);
    }
————————————————
版权声明:本文为CSDN博主「Sad67_」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42461528/article/details/127692463

Post:

using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

public class Test : MonoBehaviour
{
    private string NextSceneName;
    private ExperimentalResultData experimentalResultData;//josn 类
    void Awake()
    {
        //Application.ExternalCall("GetCookie");//GetCookie参数是js方法名字
        //login("http://st.....?xh=1656825032337321986&user=学号&userType=null&username=0名&resid=70&secret=db1ae4ca30cc1b7a2d41a56e792d9659l");


        experimentalResultData = new ExperimentalResultData();
        experimentalResultData.user = "13800138000";
        experimentalResultData.resid = 123456;
        experimentalResultData.secret = "fdef50a7bfa9360151b5eb71d127bbbe";
        experimentalResultData.status = 1;
        experimentalResultData.score = 80;
        experimentalResultData.timeUsed = 900;
        List steps_ = new List();
        StepsItem stepsItem = new StepsItem();
        stepsItem.title = "实验步骤01";
        stepsItem.timeUsed =120;
        stepsItem.expectTime = 150;
        stepsItem.maxScore = 10;
        stepsItem.score = 10;
        stepsItem.repeatCount = 1;
        steps_.Add(stepsItem);
        experimentalResultData.steps = steps_;

        //测试
        StartCoroutine(Upload(GetJsonWriter(experimentalResultData)));
        StartCoroutine(Upload02(GetJsonWriter(experimentalResultData)));
        StartCoroutine(SendWebRequest(GetJsonWriter(experimentalResultData)));
        StartCoroutine(GetSenPost(GetJsonWriter(experimentalResultData)));
    }
   
    public void OnCookie_Callback(string cookie)
    {
        Debug.Log("收到cookie=" + cookie);
        if (string.IsNullOrEmpty(cookie))
        {
            Debug.Log("----------cookie=null,返回登录界面");
            NextSceneName = "Login";
           // ILoadScene(NextSceneName);
        }
        else
        {
            Debug.Log("--------------返回大厅");
            NextSceneName = "Main";
            //PM_JsonClass.Instance.serviceTypeBo = true;
            //方法二:用于 WebGL端  加载文件
           // StartCoroutine(GetServerIPJson(cookie));
        }
    }

    private void login(string cookie)
    {
        var temps = cookie.Split('&');

        var xh = "";//学号
        var user = "";//用户登录账号
        var userTyp = "";//用户类型:1-老师,2-学生,3-社会人士
        var username = "";//用户姓名
        var resid = "";//资源id
        var secret = "";//资源密钥md5值:md5(资源密钥)
        for (int i = 0; i < temps.Length; i++)
        {
            // Debug.Log("- GetCookie_Callback -temps[i=]" + temps[i]);
            if (temps[i].Contains("xh="))
            {
                string str = temps[i].Replace("xh=", "").Trim();
                var list = str.Split('?');
                xh = list[1];
            }
            else if (temps[i].Contains("user="))
            {
                user = temps[i].Replace("user=", "").Trim();
            }
            else if (temps[i].Contains("userType="))
            {
                userTyp = temps[i].Replace("userType=", "").Trim();
            }
            else if (temps[i].Contains("username="))
            {
                username = temps[i].Replace("username=", "").Trim();
            }
            else if (temps[i].Contains("resid="))
            {
                resid = temps[i].Replace("resid=", "").Trim();
            }
            else if (temps[i].Contains("secret="))
            {
                secret = temps[i].Replace("secret=", "").Trim();
            }
            
        }

        Debug.Log($"-----------返回地址栏的信息---  ,xh={xh}, user={user}, userTyp={userTyp}, username={username}, resid={resid}, secret={secret}");
 

    }
   

    string url = "http://........";//请求地址
    string jsonData = "";//需要上传的json数据

    /// 
    /// Json转string
    /// 
    /// Json
    /// 
    private string GetJsonWriter(ExperimentalResultData experimentalResultData_)
    {
        JsonWriter tdata = new JsonWriter();
        tdata.WriteObjectStart();

        tdata.WritePropertyName("user");//
        tdata.Write(experimentalResultData_.user);
   
        tdata.WritePropertyName("resid");//
        tdata.Write(experimentalResultData_.resid);
       
        tdata.WritePropertyName("secret");//
        tdata.Write(experimentalResultData_.secret);
      
        tdata.WritePropertyName("status");//
        tdata.Write(1);

        tdata.WritePropertyName("score");//
        tdata.Write(experimentalResultData_.score);

        tdata.WritePropertyName("timeUsed");//
        tdata.Write(experimentalResultData_.timeUsed);

        tdata.WritePropertyName("stepDetails");//步骤List

        tdata.WriteArrayStart();
        for (int i = 0; i < experimentalResultData_.steps.Count; i++)
        {
            tdata.WriteObjectStart();
            tdata.WritePropertyName("title");// 
            tdata.Write(experimentalResultData_.steps[i].title);

            tdata.WritePropertyName("timeUsed");//
            tdata.Write(experimentalResultData_.steps[i].timeUsed);

            tdata.WritePropertyName("expectTime");//
            tdata.Write(experimentalResultData_.steps[i].expectTime);

            tdata.WritePropertyName("maxScore");//
            tdata.Write(experimentalResultData_.steps[i].maxScore);

            tdata.WritePropertyName("score");//
            tdata.Write(experimentalResultData_.steps[i].score);

            tdata.WritePropertyName("repeatCount");//
            tdata.Write(experimentalResultData_.steps[i].repeatCount);

            tdata.WriteObjectEnd();
        }
        tdata.WriteArrayEnd();




        tdata.WriteObjectEnd();

        return tdata.ToString();
    }

    /// 
    /// 
    /// 
    /// 
    /// 
    IEnumerator GetSenPost(string buffer)
    {
        //Debug.LogError("buffer: " + buffer);
        Dictionary headers = new Dictionary();
        headers["Content-Type"] = "application/x-www-form-urlencoded";
        byte[] data2 = Encoding.GetEncoding("utf-8").GetBytes(buffer);
        Debug.LogError("data2: " + data2);
        WWW www = new WWW(url, data2, headers);
        yield return www;
        if (www.error != null)
        {
            Debug.Log(www.error);
            yield return null;
        }
        else
        {
            Debug.Log("发送成功: " + www.text);
        }
    }
    /// 
    /// 
    /// 
    /// 
    /// 
    public IEnumerator SendWebRequest(string msg)
    {
        LitJson.JsonData data = new LitJson.JsonData
        {
            ["jsonStr"] = msg
        };
        Debug.LogError("postData: " + data);

        //Post网络请求
        using (UnityWebRequest request = UnityWebRequest.Post(url, UnityWebRequest.kHttpVerbPOST))
        {
            byte[] postBytes = Encoding.UTF8.GetBytes(data.ToJson());
            request.uploadHandler = new UploadHandlerRaw(postBytes);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            yield return request.SendWebRequest();
            if (!request.isNetworkError && !request.isHttpError)
            {
                Debug.Log("成功!"+ request);
            }
            else
            {
                Debug.LogError($"发起网络请求失败: 确认过闸接口 -{request.error}");
            }
        }
    }

    /// 
    /// 
    /// 
    /// 
    /// 
    IEnumerator Upload(string jsonData)
    {
        WWWForm form = new WWWForm();
        form.AddField("data", jsonData);
        Debug.Log("data:" + jsonData);

        UnityWebRequest webRequest = UnityWebRequest.Post(url, form);

        yield return webRequest.SendWebRequest();

        if (webRequest.isHttpError || webRequest.isNetworkError)
            Debug.Log(webRequest.error);
        else
            Debug.Log(webRequest.downloadHandler.text);
    }
    /// 
    /// 
    /// 
    /// 
    /// 
    IEnumerator Upload02(string str)
    {
        WWWForm form = new WWWForm();
        form.AddField("data", str);

        UnityWebRequest webRequest = UnityWebRequest.Post(url, form);

        yield return webRequest.SendWebRequest();

        if (webRequest.isHttpError || webRequest.isNetworkError)
            Debug.Log(webRequest.error);
        else
            Debug.Log(webRequest.downloadHandler.text);
    }
    private void ILoadScene(string nextSceneName)
    {
        //LoadSceneMode.Single:销毁当前场景,加载要加载的场景
        SceneManager.LoadScene(nextSceneName, LoadSceneMode.Single);
    }

}

实测post 成功:

using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

public class Test : MonoBehaviour
{
    private string NextSceneName;
    private ExperimentalResultData experimentalResultData;
    void Awake()
    {
        //Application.ExternalCall("GetCookie");//GetCookie参数是js方法名字
        //login("http://?xh=1656825032337321986&user=学号&userType=null&username=0名&resid=70&secret=db1ae4ca30cc1b7a2d41a56e792d9659l");

        
           // "user":"15183866055","userType":3,"resid":82,"secret":"07aa1387544ac19ea2ec0b978191943c","status":0,"score":80,"timeUsed":120,"steps":

        experimentalResultData = new ExperimentalResultData();
        experimentalResultData.user = "15183866055";
        experimentalResultData.resid = 82;
        experimentalResultData.secret = "07aa1387544ac19ea2ec0b978191943c";
        experimentalResultData.status = 0;
        experimentalResultData.score = 100;
        experimentalResultData.timeUsed = 120;
        experimentalResultData.userType = 3;
        List steps_ = new List();
        StepsItem stepsItem = new StepsItem();
        stepsItem.title = " 测试999";
        stepsItem.timeUsed =120;
        stepsItem.expectTime = 150;
        stepsItem.maxScore = 10;
        stepsItem.score = 10;
        stepsItem.repeatCount = 1;
        steps_.Add(stepsItem);
        experimentalResultData.steps = steps_;

        //测试
        //UnityWebRequest
        StartCoroutine(SendWebRequest(GetJsonWriter(experimentalResultData)));
       
        
    }
   
    public void OnCookie_Callback(string cookie)
    {
        Debug.Log("收到cookie=" + cookie);
        if (string.IsNullOrEmpty(cookie))
        {
            Debug.Log("----------cookie=null,返回登录界面");
            NextSceneName = "Login";
           // ILoadScene(NextSceneName);
        }
        else
        {
            Debug.Log("--------------返回大厅");
            NextSceneName = "Main";
            //PM_JsonClass.Instance.serviceTypeBo = true;
            //方法二:用于 WebGL端  加载文件
           // StartCoroutine(GetServerIPJson(cookie));
        }
    }

    private void login(string cookie)
    {
        var temps = cookie.Split('&');

        var xh = "";//学号
        var user = "";//用户登录账号
        var userTyp = "";//用户类型:1-老师,2-学生,3-社会人士
        var username = "";//用户姓名
        var resid = "";//资源id
        var secret = "";//资源密钥md5值:md5(资源密钥)
        for (int i = 0; i < temps.Length; i++)
        {
            // Debug.Log("- GetCookie_Callback -temps[i=]" + temps[i]);
            if (temps[i].Contains("xh="))
            {
                string str = temps[i].Replace("xh=", "").Trim();
                var list = str.Split('?');
                xh = list[1];
            }
            else if (temps[i].Contains("user="))
            {
                user = temps[i].Replace("user=", "").Trim();
            }
            else if (temps[i].Contains("userType="))
            {
                userTyp = temps[i].Replace("userType=", "").Trim();
            }
            else if (temps[i].Contains("username="))
            {
                username = temps[i].Replace("username=", "").Trim();
            }
            else if (temps[i].Contains("resid="))
            {
                resid = temps[i].Replace("resid=", "").Trim();
            }
            else if (temps[i].Contains("secret="))
            {
                secret = temps[i].Replace("secret=", "").Trim();
            }
            
        }

        Debug.Log($"-----------返回地址栏的信息---  ,xh={xh}, user={user}, userTyp={userTyp}, username={username}, resid={resid}, secret={secret}");
 

    }
   

    string url = "http://";//请求地址
    string jsonData = "";//需要上传的json数据

    /// 
    /// Json转string
    /// 
    /// Json
    /// 
    private string GetJsonWriter(ExperimentalResultData experimentalResultData_)
    {
        JsonWriter tdata = new JsonWriter();
        tdata.WriteObjectStart();

        tdata.WritePropertyName("user");//
        tdata.Write(experimentalResultData_.user);
   
        tdata.WritePropertyName("resid");//
        tdata.Write(experimentalResultData_.resid);
       
        tdata.WritePropertyName("secret");//
        tdata.Write(experimentalResultData_.secret);
      
        tdata.WritePropertyName("status");//
        tdata.Write(1);

        tdata.WritePropertyName("score");//
        tdata.Write(experimentalResultData_.score);

        tdata.WritePropertyName("timeUsed");//
        tdata.Write(experimentalResultData_.timeUsed);

        tdata.WritePropertyName("userType");//
        tdata.Write(experimentalResultData_.userType);

        tdata.WritePropertyName("steps");//步骤List

        tdata.WriteArrayStart();
        for (int i = 0; i < experimentalResultData_.steps.Count; i++)
        {
            tdata.WriteObjectStart();
            tdata.WritePropertyName("title");// 
            tdata.Write(experimentalResultData_.steps[i].title);

            tdata.WritePropertyName("timeUsed");//
            tdata.Write(experimentalResultData_.steps[i].timeUsed);

            tdata.WritePropertyName("expectTime");//
            tdata.Write(experimentalResultData_.steps[i].expectTime);

            tdata.WritePropertyName("maxScore");//
            tdata.Write(experimentalResultData_.steps[i].maxScore);

            tdata.WritePropertyName("score");//
            tdata.Write(experimentalResultData_.steps[i].score);

            tdata.WritePropertyName("repeatCount");//
            tdata.Write(experimentalResultData_.steps[i].repeatCount);

            tdata.WriteObjectEnd();
        }
        tdata.WriteArrayEnd();




        tdata.WriteObjectEnd();

        return tdata.ToString();
    }

   
    /// 
    /// 
    /// 
    /// 
    /// 
    public IEnumerator SendWebRequest(string msg)
    {
        //Debug.LogError("msg: " + msg);
        //LitJson.JsonData data = new LitJson.JsonData()
        //{
        //    ["Data"] = msg
        //};
        //data = JsonUtility.ToJson(msg);
        //Post网络请求
        using (UnityWebRequest request = UnityWebRequest.Post(url, UnityWebRequest.kHttpVerbPOST))
        {
            byte[] postBytes = Encoding.UTF8.GetBytes(msg);
            request.uploadHandler = new UploadHandlerRaw(postBytes);
            request.downloadHandler = new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
            yield return request.SendWebRequest();
            if (!request.isNetworkError && !request.isHttpError)
            {
                Debug.Log("SendWebRequest 成功:  " + request.downloadHandler.text);
            }
            else
            {
                Debug.LogError($"发起网络请求失败: 确认过闸接口 -{request.error}");
            }
        }
    }
   
   

}

post参考方案:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System;
using UnityEngine;
using LitJson;

public class ReadJsondata : MonoBehaviour
{
    HttpWebRequest request;// 声明一个HttpWebRequest请求
    Stream reqstream;//获取一个请求流
    HttpWebResponse response; //接收返回来的数据
    Stream streamReceive;//获取响应流

    string json;
    string JsonPath;

    private ExperimentalResultData experimentalResultData;
    private void Awake()
    {
        experimentalResultData = new ExperimentalResultData();
        experimentalResultData.user = "13800138000";
        experimentalResultData.resid = 123456;
        experimentalResultData.secret = "fdef50a7bfa9360151b5eb71d127bbbe";
        experimentalResultData.status = 1;
        experimentalResultData.score = 80;
        experimentalResultData.timeUsed = 900;
        experimentalResultData.userType = 3;
        List steps_ = new List();
        StepsItem stepsItem = new StepsItem();
        stepsItem.title = "实验步骤01";
        stepsItem.timeUsed = 120;
        stepsItem.expectTime = 150;
        stepsItem.maxScore = 10;
        stepsItem.score = 10;
        stepsItem.repeatCount = 1;
        steps_.Add(stepsItem);
        experimentalResultData.steps = steps_;
        json = GetJsonWriter(experimentalResultData);
        SendDataToService();
    }
    /// 
    /// Json转string
    /// 
    /// Json
    /// 
    private string GetJsonWriter(ExperimentalResultData experimentalResultData_)
    {
        JsonWriter tdata = new JsonWriter();
        tdata.WriteObjectStart();

        tdata.WritePropertyName("user");//
        tdata.Write(experimentalResultData_.user);

        tdata.WritePropertyName("resid");//
        tdata.Write(experimentalResultData_.resid);

        tdata.WritePropertyName("secret");//
        tdata.Write(experimentalResultData_.secret);

        tdata.WritePropertyName("status");//
        tdata.Write(1);

        tdata.WritePropertyName("score");//
        tdata.Write(experimentalResultData_.score);

        tdata.WritePropertyName("timeUsed");//
        tdata.Write(experimentalResultData_.timeUsed);

        tdata.WritePropertyName("stepDetails");//步骤List

        tdata.WriteArrayStart();
        for (int i = 0; i < experimentalResultData_.steps.Count; i++)
        {
            tdata.WriteObjectStart();
            tdata.WritePropertyName("title");// 
            tdata.Write(experimentalResultData_.steps[i].title);

            tdata.WritePropertyName("timeUsed");//
            tdata.Write(experimentalResultData_.steps[i].timeUsed);

            tdata.WritePropertyName("expectTime");//
            tdata.Write(experimentalResultData_.steps[i].expectTime);

            tdata.WritePropertyName("maxScore");//
            tdata.Write(experimentalResultData_.steps[i].maxScore);

            tdata.WritePropertyName("score");//
            tdata.Write(experimentalResultData_.steps[i].score);

            tdata.WritePropertyName("repeatCount");//
            tdata.Write(experimentalResultData_.steps[i].repeatCount);

            tdata.WriteObjectEnd();
        }
        tdata.WriteArrayEnd();




        tdata.WriteObjectEnd();

        return tdata.ToString();
    }

    //发送数据到服务器
    public void SendDataToService()
    {
        string urlstr = "http://xnfz.hwadee.cn:880/api/report" + json;//json字符串格式必须要对

        string recive = GetResponseData(json, urlstr);
        Debug.LogError(recive.ToString());
    }

    public string GetResponseData(string JSONData, string Url)
    {
        try
        {
            byte[] bytes = Encoding.UTF8.GetBytes(JSONData); //将参数字符串转换成字节数组。
              /* HttpWebRequest*/
            request = (HttpWebRequest)WebRequest.Create(Url);// 声明一个HttpWebRequest请求
            request.Method = "POST";///设置请求模式
            request.KeepAlive = true;
            request.ContentLength = bytes.Length; //设置请求内容大小,当然就设置成我们的参数字节数据大小。
            request.ContentType = "application/json";//设置ContntType("application/json;charset=UTF-8") ,这句很重要,否则无法传递参数ContntType(""text/xml")
            /* Stream*/
            reqstream = request.GetRequestStream();//  //发送post的请求,获取请求流
            reqstream.Write(bytes, 0, bytes.Length);// 将参数字节数组写入到请求流里
            reqstream.Close();
            request.Timeout = 90000; //设置连接超时时间
            request.Headers.Set("paramaters", "no-cache");//paramaters就是服务接口函数的参数名

            //接收返回来的数据
            /*HttpWebResponse*/
            response = (HttpWebResponse)request.GetResponse(); //执行请求,获取响应对象
            /* Stream*/
            streamReceive = response.GetResponseStream();//获取响应流
            Encoding encoding = Encoding.UTF8;
            StreamReader streamReader = new StreamReader(streamReceive, encoding);//创建流读取对象
            string strResult = streamReader.ReadToEnd();// 读取响应流
            // response.Close();
            //streamReceive.Dispose();关闭响应流
            streamReceive.Close();
            streamReader.Dispose();

            return strResult;

        } 

        catch (WebException e)
        {
            // return string.Empty;
            WebResponse wr = e.Response; using (StreamReader reader = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8)) { string value = reader.ReadToEnd(); return "H" + value; }
        }
        finally
        {
            if (reqstream != null)
            {
                reqstream.Close();
            }
            if (streamReceive != null)
            {
                streamReceive.Close();
            }
            if (response != null)
            {
                response.Close();
            }
            //很多时候释放了Stream和Response还不够,客户端的Request还是在保持着,需要等垃圾回收器来回收,所以一般很容易阻塞,导致请求发送不出去。加上这个就是让HttpWebRequest实例在不需要的时候及时释放资源。这样可以重复使用而不会阻塞。
            if (request != null)
            {
                request.Abort();
            }
        }

    }
}

你可能感兴趣的:(Unity,C#,unity,http,java)