WebReqManager

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

public class WebReqManager : MonoBehaviour
{
    public static WebReqManager instance;

    private void Awake()
    {
        instance = this;
    }

    /// <summary>
    /// 发送Get请求
    /// </summary>
    /// <param name="url">接口地址</param>
    /// <param name="respAction">响应内容回调</param>
    /// <param name="headerName">Header键</param>
    /// <param name="headerValues">Header值</param>
    /// <param name="param">拼接的参数名</param>
    /// <param name="values">拼接的参数值</param>
    public void RequestUrlByGet(string url, Action<string,string> respAction, string[] headerName = null, string[] headerValues = null, string[] param = null, string[] values = null)
    {
        string paramUrl = url;
        if (param != null)
        {
            for (int i = 0; i < param.Length; i++)
            {
                if (i == 0)
                {
                    paramUrl = paramUrl + "?";
                }
                else
                {
                    paramUrl = paramUrl + "&";
                }
                paramUrl = paramUrl + param[i] + "=" + values[i];
            }
        }

        StartCoroutine(ReqUrlByGet(paramUrl, respAction, headerName, headerValues));
    }

    /// <summary>
    /// 发送Post请求(form表单)
    /// </summary>
    /// <param name="url">接口地址</param>
    /// <param name="respAction">响应内容回调</param>
    /// <param name="form">form表单</param>
    /// <param name="headerName">Header键</param>
    /// <param name="headerValues">Header值</param>
    public void RequestUrlByPost(string url, Action<string, string> respAction, WWWForm form, string[] headerName = null, string[] headerValues = null)
    {
        StartCoroutine(ReqUrlByPost(url, respAction, form, headerName, headerValues));
    }

    /// <summary>
    /// 发送Post请求(json数据)
    /// </summary>
    /// <param name="url">接口地址</param>
    /// <param name="respAction">响应内容回调</param>
    /// <param name="json">json数据</param>
    /// <param name="headerName">Header键</param>
    /// <param name="headerValues">Header值</param>
    public void RequestUrlByPost(string url, Action<string, string> respAction, string json, string[] headerName = null, string[] headerValues = null)
    {
        StartCoroutine(ReqUrlByPost(url, respAction, json, headerName, headerValues));
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="url">接口地址</param>
    /// <param name="respAction">响应内容回调</param>
    /// <param name="fileFullPath">文件路径</param>
    /// <param name="fieldName">上传的参数名</param>
    /// <param name="headerName">Header键</param>
    /// <param name="headerValues">Header值</param>
    public void UploadFileByPost(string url, Action<string, string> respAction, string fileFullPath, string fieldName, string[] headerName = null, string[] headerValues = null)
    {
        StartCoroutine(ReqUrlByPost(url, respAction, fileFullPath, fieldName, headerName, headerValues));
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="url">下载链接</param>
    /// <param name="respAction">响应内容回调(返回文件保存的路径)</param>
    /// <param name="progressAction">下载进度回调</param>
    public void DownloadFile(string url, Action<string, string> respAction, Action<float> progressAction = null)
    {
        StartCoroutine(ReqDownloadFile(url, respAction, progressAction));
    }

    IEnumerator ReqUrlByGet(string url, Action<string, string> responseAction, string[] headerName = null, string[] headerValues = null)
    {
        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            if (headerName != null)
            {
                for (int i = 0; i < headerName.Length; i++)
                {
                    request.SetRequestHeader(headerName[i], headerValues[i]);
                }
            }

            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("UnityWebRequest Error: " + request.error);
                if (responseAction != null) responseAction.Invoke(request.error,"");
            }
            else
            {
                if (responseAction != null) responseAction.Invoke("",request.downloadHandler.text);
            }
        }
    }

    IEnumerator ReqUrlByPost(string url, Action<string, string> respAction, WWWForm form, string[] headerName, string[] headerValues)
    {
        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            if (headerName != null)
            {
                for (int i = 0; i < headerName.Length; i++)
                {
                    request.SetRequestHeader(headerName[i], headerValues[i]);
                }
            }

            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("UnityWebRequest Error: " + request.error);
                if (respAction != null) respAction.Invoke(request.error,"");
            }
            else
            {
                if (respAction != null) respAction.Invoke("",request.downloadHandler.text);
            }
        }
    }

    IEnumerator ReqUrlByPost(string url, Action<string, string> respAction, string json, string[] headerName = null, string[] headerValues = null)
    {
        using (UnityWebRequest request = new UnityWebRequest(url, "POST"))
        {
            byte[] bytes = Encoding.UTF8.GetBytes(json);
            request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bytes);
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

            if (headerName != null)
            {
                for (int i = 0; i < headerName.Length; i++)
                {
                    request.SetRequestHeader(headerName[i], headerValues[i]);
                }
            }

            // 发送请求
            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("UnityWebRequest Error: " + request.error);
                if (respAction != null) respAction.Invoke(request.error,"");
            }
            else
            {
                if (respAction != null) respAction.Invoke("",request.downloadHandler.text);
            }
        }
    }

    IEnumerator ReqUrlByPost(string url, Action<string, string> respAction, string fileFullPath, string fieldName, string[] headerName, string[] headerValues)
    {
        byte[] fileByte = File.ReadAllBytes(fileFullPath);
        WWWForm form = new WWWForm();
        form.AddBinaryData(fieldName, fileByte, Path.GetFileName(fileFullPath));

        using (UnityWebRequest request = UnityWebRequest.Post(url, form))
        {
            if (headerName != null)
            {
                for (int i = 0; i < headerName.Length; i++)
                {
                    request.SetRequestHeader(headerName[i], headerValues[i]);
                }
            }

            // 发送请求
            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("UnityWebRequest Error: " + request.error);
                if (respAction != null) respAction.Invoke(request.error,"");
            }
            else
            {
                if (respAction != null) respAction.Invoke("",request.downloadHandler.text);
            }
        }
    }

    IEnumerator ReqDownloadFile(string url, Action<string, string> respAction, Action<float> progressAction = null)
    {
        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            string fileName = Path.GetFileName(url);
            request.SendWebRequest();

            if (request.isHttpError || request.isNetworkError)
            {
                respAction.Invoke(request.error,"");
            }
            while (!request.isDone)
            {
                if (progressAction != null)
                    progressAction.Invoke(request.downloadProgress);
                yield return 0;
            }
            if (request.isDone)
            {
                if (progressAction != null)
                    progressAction.Invoke(1f);

                string savePath = Path.Combine(Application.persistentDataPath, fileName);
                using (FileStream fs = new FileStream(savePath, FileMode.Create))
                {
                    byte[] data = request.downloadHandler.data;
                    fs.Write(data, 0, data.Length);
                }

                respAction.Invoke("",savePath);
            }
        }
    }
}