杂项

当前位置:首页>技术博客>杂项
全部 15 TFrame框架 2 游戏渲染 0 编辑器扩展 0 性能优化 3 SDK 4 数据结构和算法 1 杂项 5

Unity发送GET和POST请求

时间:2021-06-18   访问量:1222


使用前提


相关代码


用的是协程,发送POST和GET的函数:


/// <summary>
/// UnityWebRequest请求返回的内容
/// </summary>
public class WebResponseData
{
    public long Code { get; set; }
    public string Error { get; set; }
    public Dictionary<string, string> Headers { get; set; }
    public string Text { get; set; }
    public byte[] Bytes { get; set; }
}

public static class HttpUltility
{
    /// <summary>
    /// 发送POST请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headerDic">POST请求的headers</param>
    /// <param name="bodyJsonData">Body数据</param>
    /// <param name="timeout">超时</param>
    /// <param name="callback">回调,如果参数为null,表示此次请求失败了。</param>
    /// <returns></returns>
    public static IEnumerator IE_SendPostRequest(string url, Dictionary<string, string> headerDic, JsonData bodyJsonData, int timeout, Action<WebResponseData> callback)
    {
        string postBodyData = ConvertToJson(bodyJsonData);
        using (UnityWebRequest request = UnityWebRequest.Post(url, "POST"))
        {
            //超时限制
            request.timeout = timeout;
            byte[] postBytes = Encoding.UTF8.GetBytes(postBodyData);
            request.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);

            //设置POST请求的header
            if (headerDic != null)
            {
                foreach (var item in headerDic)
                {
                    request.SetRequestHeader(item.Key, item.Value);
                }
            }

            yield return request.SendWebRequest();
            WebResponseData response = null;
            if (request.isNetworkError || request.isHttpError)
            {
                Debug.LogError(request.error);
            }
            else
            {
                response = new WebResponseData();
                response.Code = request.responseCode;
                response.Headers = request.GetResponseHeaders();
                response.Error = request.error;
                response.Text = request.downloadHandler.text;
                response.Bytes = request.downloadHandler.data;

            }
            request.Abort();
            request.disposeDownloadHandlerOnDispose = true;
            request.Dispose();
            if (callback != null)
            {
                callback(response);
            }
        }
    }

    /// <summary>
    /// 发送GET请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="headerDic">POST请求的headers</param>
    /// <param name="bodyJsonData">Body数据,会拼接在URL中</param>
    /// <param name="timeout">超时</param>
    /// <param name="callback">回调,如果参数为null,表示此次失败了。</param>
    /// <returns></returns>
    public static IEnumerator IE_SendGetRequest(string url, Dictionary<string, string> headerDic, JsonData paramJsonData, int timeout, Action<WebResponseData> callback)
    {

        //需要将paramJsonData数据拼接到URL中
        var newURL = url;
        var json = ConvertToJson(paramJsonData);
        Dictionary<string, object> dict = JsonMapper.ToObject<Dictionary<string, object>>(json);
        if (dict != null && dict.Count > 0)
        {
            var tempContent = string.Empty;
            int i = 0;
            foreach (var item in dict)
            {
                if (i > 0)
                {
                    tempContent = UT_Helper.BuildString2(tempContent, "&");
                }
                tempContent = UT_Helper.BuildString2(tempContent, item.Key, "=", item.Value.ToString());
                i++;
            }
            newURL = UT_Helper.BuildString2(newURL, "?", tempContent);
        }
        newURL = newURL.Replace("", "/");
        using (UnityWebRequest request = UnityWebRequest.Get(newURL))
        {
            //超时限制
            request.timeout = timeout;

            //设置GET请求的header

            if (headerDic != null && headerDic.Count > 0)
            {
                foreach (var tempKey in headerDic.Keys)
                {
                    request.SetRequestHeader(tempKey, headerDic[tempKey]);
                }
            }

            yield return request.SendWebRequest();
            WebResponseData response = null;
            if (request.isNetworkError || request.isHttpError)
            {
                Debug.LogError(request.error);
            }
            else
            {
                response = new WebResponseData();
                response.Code = request.responseCode;
                response.Headers = request.GetResponseHeaders();
                response.Error = request.error;
                response.Text = request.downloadHandler.text;
                response.Bytes = request.downloadHandler.data;

            }
            request.Abort();
            request.disposeDownloadHandlerOnDispose = true;
            request.Dispose();
            if (callback != null)
            {
                callback(response);
            }
        }
    }

    static string ConvertToJson(object obj)
    {
        var s = JsonMapper.ToJson(obj);
        Regex reg = new Regex(@"(?i)[uU]([0-9a-f]{4})");
        s = reg.Replace(s, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
        return s;
    }
}


上一篇:Unity接入中宣部防沉迷实名认证之AES-128/GCM + BASE64加密(二)

下一篇:Unity中EXE弹出Windows提示框

发表评论:

评论记录:

未查询到任何数据!