当前位置:   article > 正文

Unity- BestHTTP数据请求及文件下载_unity besthttp

unity besthttp

Unity (BestHTTP)数据请求及文件下载

Unity工程中关于HTTP的使用非常常见,Unity本身集成的WWW便可以进行网络请求处理,但是,WWW本身却有很多的局限性,而BestHttp插件却把HTTP这一块处理的很好,今天学习了一下,并做个简单的笔记,写一个小Demo

创建APIRequestTest对象来管理程序执行过程中关于HTTP的数据请求及下载 这个脚本中有请求完成回调,下载进度回调及下载资源完成回调,基本能满足常规使用,代码注释很清晰

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using BestHTTP;
using UnityEngine;

public class APIRequestTest 
{
    public delegate void HTTPRequestCallBack(APIRequestTest apiRequest,bool isSuccess,string responseText);
    public delegate void HTTPDownProgressCallBack(APIRequestTest apiRequest,float progress);
    public delegate void HTTPDownCompleteCallBack(APIRequestTest apiRequest,bool isSuccess,int code,string savePath);
    private HTTPRequestCallBack requestCallBack;//请求完成回调
    private HTTPDownProgressCallBack downProgressCallBack;//下载进度回调
    private HTTPDownCompleteCallBack downCompleteCallBack;//下载完成回调

    //正式服务器根路径
    private static string baseUrl = "";
    //测试服务器根路径
    private static string testBaseUrl = "http://192.168.2.129:55555/v1/";
    //是否用测试服务器
    public static bool useTestServer = true;

    private HTTPRequest request;
    private TimeSpan requestTimeOut = TimeSpan.FromSeconds(30);//请求超时时间设置 30S

    private string downSavePath;//下载资源的本地保存路径
    private int downFileCount = -1;//需要下载资源的长度
    private int downedFileCount = 0;//已经下载资源的长度
    private float downProgressValue = 0;//下载资源的进度

    private APIRequestTest(string _baseUrl=null) {
		if (!string.IsNullOrEmpty(_baseUrl))
		{
			baseUrl = _baseUrl;
		}
	}

    //创建请求对象
	public static APIRequestTest Create(string _baseUrl=null) {
		if (useTestServer)
		{
			_baseUrl = testBaseUrl;
		}
		return new APIRequestTest(_baseUrl);
	}

    //设置请求超时时间
    public APIRequestTest SetTimeOut(double seconds) {
        if (seconds<=0)
        {
            return this;
        }
        requestTimeOut = TimeSpan.FromSeconds(seconds);
        return this;
    }

    //设置请求优先级  优先级较高的请求将比优先级较低的请求更快地从请求队列中选择。
    public APIRequestTest SetPriority(int priority) {
        if (request!=null)
        {
            request.Priority = priority;
        }
        return this;
    }

    #region 数据请求

    //发送请求
    public APIRequestTest Send(HTTPMethods method,string url,Dictionary<string,string> paramsDict, HTTPRequestCallBack sendCallBack =null) {
        requestCallBack = sendCallBack;
        if (Application.internetReachability==NetworkReachability.NotReachable)//没有网络连接
        {
            Debug.LogError("【 检查设备是否可以访问网络!!! 】");
            requestCallBack?.Invoke(this,false,"设备无法进行网络连接");
            return this;
        }
        if (method ==HTTPMethods.Get)
        {
            SendGetMethod(url,paramsDict);
        }
        else if (method==HTTPMethods.Post)
        {
            SendPostMethod(url,paramsDict);
        }
        if (request==null)
        {
            Debug.LogError("【 创建HTTPRequest失败!!! 】");
            requestCallBack?.Invoke(this, false, "创建HTTPRequest失败");
            return this;
        }
        SetRequestHeaders(request);
        //禁止缓存
        request.DisableCache = true;
        //设置超时时间
        request.Timeout = requestTimeOut;
        //发送请求
        request.Send();
        return this;
    }

    //终止请求
    public APIRequestTest Abort() {
        if (request!=null)
        {
            request.Abort();
        }
        return this;
    }

    //设置请求头
    public void SetRequestHeaders(HTTPRequest _request) {

        //_request.SetHeader("name","value");

    }

    //Get方式请求数据
    void SendGetMethod(string url,Dictionary<string,string> paramsDict) {
        string requestUrl = baseUrl + url+"?";
        if (paramsDict!=null&&paramsDict.Count>0)
        {
            int id = 0;
            foreach (var item in paramsDict.Keys)
            {
                string key = item;
                string value = paramsDict[key];
                if (id < paramsDict.Count - 1)
                {
                    requestUrl += key + "=" + value + "&";
                }
                else {
                    requestUrl += key + "=" + value;
                }
                id++;
            }
        }
        Uri uri = new Uri(requestUrl);
        request = new HTTPRequest(uri,HTTPMethods.Get, OnRequestFinished);
        
    }

    //Post方式请求数据
    void SendPostMethod(string url,Dictionary<string, string> paramsDict) {
        string requestUrl = baseUrl + url;
        Uri uri = new Uri(requestUrl);
        request = new HTTPRequest(uri,HTTPMethods.Post,OnRequestFinished);
        if (paramsDict!=null&&paramsDict.Count>0)
        {
            foreach (var item in paramsDict.Keys)
            {
                string key = item;
                string value = paramsDict[key];
                request.AddField(key,value);
            }
        }
        
    }

    //数据请求完成回调
    void OnRequestFinished(HTTPRequest _request, HTTPResponse response) {
        int responseCode = 0;//请求返回码
        bool isSuccess = false;
        string responseText = null;

        if (_request.State == HTTPRequestStates.Finished)//请求完成
        {
            responseCode = response.StatusCode;
            isSuccess = response.IsSuccess;
            responseText = response.DataAsText;
        }
        else if (_request.State == HTTPRequestStates.TimedOut || _request.State == HTTPRequestStates.ConnectionTimedOut)//请求或连接超时
        {
            responseText = "请求超时";
        }
        else if (_request.State == HTTPRequestStates.Error)//请求报错
        {
            if (request.Exception != null)
            {
                responseText = request.Exception.Message;
                if (string.IsNullOrEmpty(responseText))
                {
                    responseText = "请求报错";
                }
            }
            else
            {
                responseText = "请求报错";
            }
        }
        else {//其他异常
            responseText = _request.State.ToString();
        }
#if UNITY_EDITOR  //编辑器模式下打印请求数据
        string debugStr = "【HTTPRequest  State="+ _request.State.ToString()+"  isSuccess="+isSuccess+"】:";
        string url = _request.Uri.AbsoluteUri+"\n";
        debugStr = "<color=blue>"+debugStr + url+"</color>" + System.Text.RegularExpressions.Regex.Unescape(responseText);
        Debug.Log(debugStr);
#endif

        requestCallBack?.Invoke(this,isSuccess,responseText);

    }

    #endregion 


    #region 资源下载

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="url">资源url</param>
    /// <param name="savePath">保存本地的路径</param>
    /// <param name="progressCallBack">下载进度回调</param>
    /// <param name="completeCallBack">下载完成回调</param>
    /// <param name="forceDown">是否强制下载(是否替换本地文件)</param>
    public void DownFile(string url, string savePath, HTTPDownProgressCallBack progressCallBack, HTTPDownCompleteCallBack completeCallBack, bool forceDown = false) {
        downCompleteCallBack = completeCallBack;
        downProgressCallBack = progressCallBack;
        downSavePath = savePath;
        downFileCount = -1;
        downedFileCount = 0;
        if (string.IsNullOrEmpty(url)||string.IsNullOrEmpty(savePath))
        {
            Debug.LogError("【 非法的下载地址或存储地址! 】");
            downCompleteCallBack?.Invoke(this,false,300,savePath);
            return;
        }

        if (!forceDown)//非强制下载
        {
            if (File.Exists(savePath))//本地存在目标文件
            {
                if (savePath.EndsWith(".tmp", StringComparison.CurrentCulture))
                {//删除本地临时文件
                    File.Delete(savePath);
                    Debug.Log("删除文件:"+savePath);
                }
                else {
                    Debug.Log("重复资源,无需下载:"+savePath);
                    downProgressCallBack?.Invoke(this,1);
                    downCompleteCallBack?.Invoke(this, true, 200, savePath);
                    return;
                }
            }
            else {//新资源
                Debug.Log("新资源:"+savePath);
            }
        }

        Uri uri = new Uri(url);
        request = new HTTPRequest(uri,DownRequestFinished);
        request.UseStreaming = true;
        request.StreamFragmentSize = 1024 * 512;
        request.DisableCache = true;
        request.Timeout = requestTimeOut;
        request.ConnectTimeout =requestTimeOut;
        request.Send();
    }

    //下载资源请求结束回调
    private void DownRequestFinished(HTTPRequest _request, HTTPResponse response) {

        HTTPRequestStates states = _request.State;
        if (states==HTTPRequestStates.Processing)//数据请求中
        {
            if (downFileCount == -1)
            {
                string value = response.GetFirstHeaderValue("content-length");
                if (!string.IsNullOrEmpty(value))
                {
                    downFileCount= int.Parse(value);
                    Debug.Log("GetFirstHeaderValue content-length = " + downFileCount);
                }
            }
            List<byte[]> bytes;
            bytes = response.GetStreamedFragments();
            SaveFile(bytes);
            downProgressValue = downedFileCount / (float)downFileCount;
            downProgressCallBack?.Invoke(this,downProgressValue);
        }
        else
        if (states == HTTPRequestStates.Finished)//数据请求完成
        {
            if (response.IsSuccess)
            {
                List<byte[]> bytes;
                bytes = response.GetStreamedFragments();
                SaveFile(bytes);
                if (response.IsStreamingFinished)
                {
                    downProgressCallBack?.Invoke(this, 1);
                    downCompleteCallBack?.Invoke(this,true,response.StatusCode,downSavePath);
                }
                else {
                    Debug.LogError("【HTTPRequestStates.Finished成功,Response.IsStreamingFinished失败】");
                    downCompleteCallBack?.Invoke(this, false, response.StatusCode, downSavePath);
                }
            }
            else {

                downCompleteCallBack?.Invoke(this, false, response.StatusCode, downSavePath);
                string logMsg = string.Format("{0} - {1} - {2}", response.StatusCode, response.Message, _request.Uri.AbsoluteUri);
                Debug.LogError(logMsg);
            }
        }
        else {//数据请求失败
            Debug.LogError("DownFile失败:"+_request.State.ToString());
            downCompleteCallBack?.Invoke(this,false,-1, downSavePath);
        }

    }

    //保存资源到本地
    private void SaveFile(List<byte[]> bytes) {
        if (bytes==null||bytes.Count<=0)
        {
            return;
        }

        using (FileStream fs = new FileStream(downSavePath,FileMode.Append)) {
            for (int i = 0; i < bytes.Count; i++)
            {
                byte[] byteArr = bytes[i];
                fs.Write(byteArr,0,byteArr.Length);
                downedFileCount+=byteArr.Length;
            }
        }

    }

    #endregion 


}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337

使用

请求数据

string url = "student/report_card";
Dictionary<string, string> info = new Dictionary<string, string>();
info["lesson_id"] = "1287";
APIRequestTest.Create().Send(BestHTTP.HTTPMethods.Get, url, a, (APIRequestTest api, bool isSuccess, string responseText) =>{
     if (isSuccess)
       {
           Debug.LogError("请求成功");
       }
       else
       {
           Debug.LogError("请求失败");
       }
       Debug.LogError(responseText);
   });

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

资源下载

string downUrl = "资源网络路径";
string savePath = Application.streamingAssetsPath + "/testVideo.mp4";

APIRequestTest.Create().DownFile(downUrl, savePath, (APIRequestTest apiRequest, float value) =>
  {
      Debug.LogError(value.ToString("f2"));
  }, (APIRequestTest api, bool isSuccess, int code, string path) =>
   {
       if (isSuccess)
       {
           Debug.LogError("下载成功");
       }
       else
       {
           Debug.LogError("下载失败");
       }
       Debug.LogError(path);
   });


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/127578
推荐阅读
相关标签
  

闽ICP备14008679号