UnityWebRequest

Get方法:

using System.Collections;
using System.Collections.Generic;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;
public class UnityWebRequestTest: MonoBehaviour
{
    string url = "https://www.baidu.com/";
    void Start()
    {
        StartCoroutine(GetRequest());
    }
    public IEnumerator GetRequest()
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {

            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
            }
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
                JsonData jsonData = JsonMapper.ToObject(webRequest.downloadHandler.text);
               text = jsonDate[0]["a"].ToString();

            }
        }
    }
}

Post方法:
1、

IEnumerator HttpLogin()
    {
        url = AppConst.WebUrl;

        WWWForm form = new WWWForm();
        form.AddField("username", username);
        form.AddField("password", password);

        using (UnityWebRequest webRequest = UnityWebRequest.Post(url,form))
        {
            yield return webRequest.SendWebRequest();
            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
            }
            //代表通讯正常完成  不是代表消息接收成功;
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
            }
        }
    }

2、

public IEnumerator PostUrl(string url, string postData)
    {
        using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
        {
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
            www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
            www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            www.SetRequestHeader("Content-Type", "application/json");
            yield return www.Send();
            if (www.isError)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
            }
        }
    }
IEnumerator GetAllDevice(int AreaId, int StoreId, string str, int modelId)
    {
        Debug.Log("基地:" + AreaId + "  库区:" + StoreId + "  查询:" + str + "  ModelID:" + modelId);
        //post
        string url = AppConfig.HttpYbjURL + "biz-module-equipment/" + url_Devicelist;

        JsonData data = new JsonData();
        if (AreaId == 0)
        {
            data["belongAreaId"] = null;
        }
        else
        {
            data["belongAreaId"] = AreaId;
        }
        if (StoreId == 0)
        {
            data["belongStoreId"] = null;
        }
        else
        {
            data["belongStoreId"] = StoreId;
        }

        data["deviceNumber"] = str;
        data["modelId"] = modelId;

        byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());

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

        request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        yield return request.SendWebRequest();
        if (request.isNetworkError || request.isHttpError)
        {
            Debug.LogError(request.error);
        }
        else
        {
HttpMessageHandle_xc.Instance.DeviceListHandle(request.downloadHandler.text);
        }
    }

完整工具代码封装(转)

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

/// 
/// Http Request SDK 
/// 
public class HttpTool : MonoBehaviour
{

    private static HttpTool _instacne = null;
    public string baseUrl = "https://127.0.0.1:3000/";
    public string sKey = "zoo_visit_key";

    Dictionary requestHeader = new Dictionary();  //  header
    public static HttpTool Instance
    {
        get
        {
            if (_instacne == null)
            {
                Debug.LogError("Awake error");
            }
            return _instacne;
        }
    }

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        HttpTool._instacne = gameObject.GetComponent();

         //http header 的内容
        requestHeader.Add("Content-Type", "application/json");
        requestHeader.Add("sKey", sKey);

    }

    public void Get(string methodName, Action callback)
    {
        StartCoroutine(GetRequest(methodName, callback));
    }
    public IEnumerator GetRequest(string methodName, Action callback)
    {
        string url = baseUrl + methodName;
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            //设置header
            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, v.Value);
            }
            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }

   //jsonString 为json字符串,post提交的数据包为json
    public void Post(string methodName,string jsonString, Action callback)
    {
        StartCoroutine(PostRequest(methodName,jsonString,callback));
    }
    public IEnumerator PostRequest(string methodName, string jsonString, Action callback)
    {
        string url = baseUrl + methodName;
       // Debug.Log(string.Format("url:{0} postData:{1}",url,jsonString));
        using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
        {
            byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonString);
            webRequest.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            webRequest.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();

            foreach (var v in requestHeader)
            {
                webRequest.SetRequestHeader(v.Key, v.Value);
            }
            yield return webRequest.SendWebRequest();

            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.LogError(webRequest.error + "\n" + webRequest.downloadHandler.text);
                if (callback != null)
                {
                    callback(null);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(webRequest.downloadHandler.text);
                }
            }
        }
    }
}

你可能感兴趣的:(UnityWebRequest)