Unity UnityWebRequest 简单post get 请求

这里写自定义目录标题

UnityWebRequest 简单post get 请求

简单的请求,有需要可拓展

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Text;
using System;
using LitJson;
using SadTools;
using Http.Model;
using UnityEditor.PackageManager.Requests;

public class HttpClientVR : UnitySingleton<HttpClientVR>
{
    private static string TAG = "[HttpClient] ";
    //服务器地址
    private static string url = "https://**************/server/";
    private void Start()
    {

    }

    /// <summary>
    /// Post请求
    /// </summary>
    /// <param name="req">请求体</param>
    /// <param name="callback">接口回调</param>
    public void Post(BaseRequestModel req, Action<string> callback)
    {
        StartCoroutine(I_RequestByJsonBodyPost(url + req.type, JsonMapper.ToJson(req), callback));
    }

    /// <summary>
    /// 接口请求携程
    /// </summary>
    private static IEnumerator I_RequestByJsonBodyPost(string url, string json, Action<string> callback)
    {
        Debug.Log(TAG + url + "\n" + "RequestModel : " + json);
        var uwr = new UnityWebRequest(url, "POST");
        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        uwr.certificateHandler = new WebRequestCertificate();
        uwr.SetRequestHeader("Content-Type", "application/json");
        yield return uwr.SendWebRequest();
        if (uwr.isDone)
        {
            Debug.Log(uwr.downloadHandler.text);
            string data = uwr.downloadHandler.text;
            if (data != null && !data.Equals(""))
            {
                callback(data);
            }
            else
            {
                Debug.LogError("接口请求失败");
            }

        }
    }

    /// <summary>
    /// Get请求
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="callback">接口回调</param>
    public void Get(string url, Action<string> callback)
    {
        StartCoroutine(I_RequestGET(url, callback));
    }

    /// <summary>
    /// 接口请求携程
    /// </summary>
    private static IEnumerator I_RequestGET(string url, Action<string> 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);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值