UnityWebRequest HTTP 请求服务

UnityWebRequest HTTP 请求服务

所用到插件
LitJson链接:
链接:https://pan.baidu.com/s/1lEbQbAQNewaxs-CKahpBcA
提取码:ovt9

请求服务

using UnityEngine;
using System;
using LitJson ;
using System.Text.RegularExpressions;

/// <summary>
/// 请求服务
/// </summary>
public class RequestServer : ServerManager 
{
    /// <summary> 登录验证 </summary>
    /// <param name="action">回调函数</param>
    /// <param name="accountNumber">账号</param>
    /// <param name="password">密码</param>
    public void LoginVerification(Action<string> action, string accountNumber, string password)
    {
        Debug.Log("登录验证");
        //============JSON的生成 使用的LitJson============================
        JsonData data = new JsonData();
        //生成嵌套结构的json
        data["telphone"] = accountNumber;
        data["password"] = password;
        string json = data.ToJson();
        //避免乱码
        Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        json = reg.Replace(json, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
        Debug.Log(json);

        //url接口
        string url = ConfigManager.projectInforDataConfig.ConfigData.mServiceUrl + "customer/login";
        StartCoroutine(ServerPostUrl(url, json, action));
    }
}

服务器管理器
token 功能没有测试过

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Net;
using System.Reflection;
using UnityEngine;
using UnityEngine.Networking;

public class ServerManager : MonoBehaviour {

    /// <summary> 数据库请求 </summary>
    /// <param name="url">接口地址</param>
    /// <param name="postData">请求数据</param>
    /// <param name="action">执行回调方法</param>
    /// <returns></returns>
    protected IEnumerator ServerPostUrl(string url, string postData, Action<string> action, string token = "")
    {
        Debug.Log("Url : " + url);
        using (UnityWebRequest www = new UnityWebRequest(url, "POST"))
        {
            if (token != "")
            {
                var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
                if (property != null)
                {
                    var collection = property.GetValue(www.GetResponseHeaders(), null) as NameValueCollection;
                    collection[name] = token;
                }
            }
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postData);
            www.uploadHandler = (UploadHandler)new UploadHandlerRaw(postBytes);
            www.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
            www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            www.timeout = 30;
            yield return www.SendWebRequest();

            Debug.Log("ReponseCode : " + www.responseCode + "\nError : " + www.error);

            if (www.isHttpError || www.isNetworkError)
            {
                Debug.LogWarning("Error: " +www.error + "\n" + www.downloadHandler.text);
            }
            else
            {
                if (www.responseCode == 200)
                {
                    string text = www.downloadHandler.text;
                    Debug.Log(url + "\n" + text);
                    action(text);
                }
                else
                {                    
                    if (www.responseCode == 404)
                    {
                        Debug.LogWarning("Error : " + 404); 
                    }
                    if (www.responseCode == 500)
                    {
                        Debug.LogWarning("Error : " + 500);
                    }
                }
            }
        }               
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值