Пример #1
0
        public IObservable <UnityWebRequest> SendManifestRequest(string url)
        {
            var version = PlayerPrefs.GetInt(AssetConstant.MANIFEST_VERSION_KEY, 0);
            var hash    = AssetPath.Version2Hash(version);

            if (Caching.IsVersionCached(url, hash))
            {
                return(UnityWebRequest.Head(url).SendAsObserable()
                       .ContinueWith(operation =>
                {
                    var req = operation == null ? null : operation.webRequest;
                    if (req != null && req.GetResponseHeader(AssetConstant.HTTP_ETAG_FLAG)
                        == PlayerPrefs.GetString(AssetConstant.MANIFEST_ETAG_KEY))
                    {
                        return UnityWebRequestAssetBundle.GetAssetBundle(url, hash)
                        .SendAsObserable().Select(_ => _.webRequest);
                    }
                    else
                    {
                        hash = AssetPath.Version2Hash(version + 1);
                        return UnityWebRequestAssetBundle.GetAssetBundle(url, hash)
                        .SendAsObserable().Select(_ => _.webRequest);
                    }
                }));
            }
            else
            {
                return(UnityWebRequestAssetBundle.GetAssetBundle(url, hash)
                       .SendAsObserable().Select(_ => _.webRequest));
            }
        }
Пример #2
0
    IEnumerator PreProcessAssetRequest(Dictionary <string, AssetRequest> downlist)
    {
        foreach (KeyValuePair <string, AssetRequest> kv in downlist)
        {
#if USE_DROPBOX
            string key      = kv.Key.ToString().ToLower();
            string assetURL = String.Format("{0}{1}?dl=1", mDropboxDict[key], key);
#endif

            long fileSize = 0;
            using (var headRequest = UnityWebRequest.Head(assetURL))
            {
                yield return(headRequest.Send());

                if (headRequest.responseCode != 200)
                {
                    // TODO: Error response
                }
                else
                {
                    var contentLength = headRequest.GetResponseHeader("CONTENT-LENGTH");
                    long.TryParse(contentLength, out fileSize);

                    //byte to kb
                    mFullSize += (float)(fileSize / 1024);
                    downlist[key].LoadPath   = assetURL;
                    downlist[key].BundleSize = (fileSize / 1024);
                }
            }
        }
    }
Пример #3
0
        /// <summary>Creates a Unity Web Request from the given parameters.</summary>
        /// <param name="uri">The Request URI (URL).</param>
        /// <param name="httpRequestMethod">The HTTP Request method to use.</param>
        /// <param name="data">The Custom Data that was sent along the Request.</param>
        /// <param name="timeout">The Request timeout in seconds).</param>
        /// <returns>The created unity web request.</returns>
        public static UnityWebRequest CreateWebRequest(string uri, HttpRequestMethod httpRequestMethod = HttpRequestMethod.Get, string data = null, int timeout = 2000)
        {
            UnityWebRequest unityWebRequest;

            switch (httpRequestMethod)
            {
            case HttpRequestMethod.Post:
                unityWebRequest = UnityWebRequest.Post(uri, data);
                break;

            case HttpRequestMethod.Put:
                unityWebRequest = UnityWebRequest.Put(uri, data);
                break;

            case HttpRequestMethod.Delete:
                unityWebRequest = UnityWebRequest.Delete($"{uri}?{data}");
                break;

            case HttpRequestMethod.Head:
                unityWebRequest = UnityWebRequest.Head($"{uri}?{data}");
                break;

            default:
                unityWebRequest = UnityWebRequest.Get($"{uri}?{data}");
                break;
            }
            unityWebRequest.timeout = timeout;
            return(unityWebRequest);
        }
Пример #4
0
 public void Start()
 {
     request = UnityWebRequest.Head(url);
     request.SendWebRequest();
     progress = 0;
     isDone   = false;
 }
Пример #5
0
    private IEnumerator FileSizeUpdateAsync(string url)
    {
        if (url.IsNullOrEmpty())
        {
            // Do not continue with the coroutine
            ResetFileSizeText();
            yield break;
        }

        Debug.Log($"Fetching size of {url}");
        using (UnityWebRequest request = UnityWebRequest.Head(url))
        {
            yield return(request.SendWebRequest());

            if (request.isNetworkError || request.isHttpError)
            {
                Debug.LogError($"Error fetching size: <color='red'>{request.error}</color>");
                AddToUiLog($"Error fetching size: <color='red'>{request.error}</color>");
                ResetFileSizeText();
            }
            else
            {
                long size = Convert.ToInt64(request.GetResponseHeader("Content-Length"));
                fileSize.text = (size / 1024 / 1024) + " MB";
            }
        }
    }
Пример #6
0
        public UnityWebRequest HeadBundleRequest(DLCBundle bundle)
        {
            string          path = hostPath + SystemInfoUtil.PlatformName() + "/" + bundle.category + "/" + bundle.name;
            UnityWebRequest www  = UnityWebRequest.Head(path);

            return(www);
        }
Пример #7
0
        // TODO: simplify timeout for Unity 5.6+
        // https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequest-timeout.html
        public HTTPRequest(string url, Action <Response> callback, int timeout, HttpRequestType requestType = HttpRequestType.Get)
        {
            IsCompleted  = false;
            _requestType = requestType;

            switch (_requestType)
            {
            case HttpRequestType.Get:
                _request = UnityWebRequest.Get(url);
                break;

            case HttpRequestType.Head:
                _request = UnityWebRequest.Head(url);
                break;

            default:
                _request = UnityWebRequest.Get(url);
                break;
            }

            _request.timeout = timeout;
            _callback        = callback;

#if UNITY_EDITOR
            if (!EditorApplication.isPlaying)
            {
                Runnable.EnableRunnableInEditor();
            }
#endif
            Runnable.Run(DoRequest());
        }
Пример #8
0
        static IEnumerator CheckInternetConnection(string echoServer, Action successCallback, Action failCallback)
        {
            bool result;

            using (var request = UnityWebRequest.Head(echoServer))
            {
                request.timeout = 5;
                yield return(request.SendWebRequest());

                result = !request.isNetworkError && !request.isHttpError && request.responseCode == 200;
                if (result == false)
                {
                    Debug.LogError("---------------------->request.error:" + request.error + ",request.responseCode:" + request.responseCode);
                }
            }
            if (result == true)
            {
                Debug.Log("internet connected:" + echoServer);
                if (successCallback != null)
                {
                    successCallback();
                }
            }
            else
            {
                Debug.Log("internet not connected:" + echoServer);
                if (failCallback != null)
                {
                    failCallback();
                }
            }
        }
Пример #9
0
    // Start is called before the first frame update
    IEnumerator Start()
    {
        string path = @"F:\url.txt";

        string[] arr = File.ReadAllLines(path);
        for (int i = 0; i < arr.Length; i++)
        {
            string url = arr[i];
            url = URLHelper.UrlEncode(url);
            Debug.Log(url);
            UnityWebRequest head = UnityWebRequest.Head(url);
            yield return(head);

            long len;
            long.TryParse(head.GetResponseHeader("Content-Length"), out len);
            Debug.Log("---" + len);
            continue;
            UnityWebRequest webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);
            //webRequest.downloadHandler = new DownloadHandlerFile(filePath);
            yield return(webRequest.SendWebRequest());

            Debug.Log(webRequest.responseCode);
            if (webRequest.isNetworkError || webRequest.isHttpError)
            {
                Debug.LogError("Error:::" + webRequest.isNetworkError.ToString());
                Debug.LogError("Error:::" + webRequest.isHttpError.ToString());
                Debug.LogError("Error:::" + webRequest.ToString());
                //Debug.LogError($"{i}>>{filePath}>>{url}");
            }
        }

        yield break;
    }
Пример #10
0
        IEnumerator Head()
        {
            UnityWebRequest uwr = UnityWebRequest.Head(Url + FileName);

            yield return(uwr.Send());

            if (uwr.isError)
            {
                Debug.Log(uwr.error);
            }
            Debug.Log("responseCode:" + uwr.responseCode);
            string strLength = uwr.GetResponseHeader("Content-Length");

            if (!string.IsNullOrEmpty(strLength))
            {
                mFileSize = Convert.ToInt64(strLength);
                Debug.LogFormat("Content - Length: {0}", mFileSize);
            }
            string strDateTime = uwr.GetResponseHeader("Last-Modified");

            if (!string.IsNullOrEmpty(strDateTime))
            {
                mServerFileDateTime = DateTime.Parse(strDateTime);
                Debug.LogFormat("Last-Modified: {0}", mServerFileDateTime.ToString("yyyy.MM.dd HH:mm:ss"));
            }

            StartCoroutine(Download());
        }
Пример #11
0
        //checks for the most recent version available online
        internal void GetLatestETag(Action <AsyncOperation> onGet)
        {
            var request   = UnityWebRequest.Head(k_PackageUri);
            var operation = request.SendWebRequest();

            operation.completed += onGet;
        }
Пример #12
0
    /// <summary>
    /// 文件下载,断点续传
    /// </summary>
    /// <param name="url"></param>
    /// <param name="filePath"></param>
    /// <param name="callBack"></param>
    /// <returns></returns>
    public IEnumerator IE_DownloadFile(string url, string filePath, Action <float> callBack)
    {
        //获取要下载的文件的总大小
        var headRequest = UnityWebRequest.Head(url);

        yield return(headRequest.SendWebRequest());

        var totalLength = long.Parse(headRequest.GetResponseHeader("Content-Length"));
        //如果文件未下载,创建文件下载路径
        var dirPath = Path.GetDirectoryName(filePath);

        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
        }
        //开始下载
        FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        //获取文件现在的长度
        var fileLength = fileStream.Length;
        //创建网络请求
        var request = UnityWebRequest.Get(url);

        if (fileLength > 0)
        {
            //设置开始下载文件从什么位置开始
            request.SetRequestHeader("Range", "bytes=" + fileLength + "-"); //这句很重要
            fileStream.Seek(fileLength, SeekOrigin.Begin);                  //将该文件的指针移动到当前长度,即继续存储
        }
        float progress;                                                     //文件下载进度

        if (fileLength < totalLength)
        {
            request.SendWebRequest();
            var index = 0;
            while (!request.isDone)
            {
                yield return(new WaitForEndOfFrame());

                var buffer = request.downloadHandler.data;
                //将实时下载得到的数据存储到文件中
                if (buffer != null)
                {
                    var length = buffer.Length - index;
                    fileStream.Write(buffer, index, length);
                    index      += length;
                    fileLength += length;
                    //文件下载进度
                    progress = fileLength / (float)totalLength;
                    callBack?.Invoke(progress);
                }
            }
        }
        else
        {
            progress = 1;
            callBack?.Invoke(progress);
        }
        fileStream.Close();
        fileStream.Dispose();
    }
        /// <summary>
        /// 获取下载文件的大小和最后修改时间
        /// </summary>
        /// <param name="url"></param>
        /// <param name="onGetRemoteFileInfo"></param>
        /// <returns></returns>
        public static IEnumerator GetRemoteFileInfo(string fileName, OnGetRemoteFileInfo onGetRemoteFileInfo)
        {
            string url = BaseDownloadingURL + fileName;

            using (UnityWebRequest request = UnityWebRequest.Head(url))
            {
                yield return(request.Send());

                if (request.isError)
                {
                    string error = string.Format("GetRemoteFileInfo - url: {0}, responseCode: {1}, error: {2}",
                                                 url, request.responseCode, request.error);
                    onGetRemoteFileInfo(fileName, error, 0, DateTime.Now);
                    yield break;
                }
                string strLength = request.GetResponseHeader("Content-Length");
                if (string.IsNullOrEmpty(strLength))
                {
                    onGetRemoteFileInfo(fileName, "GetRemoteFileInfo - can not get Content-Length", 0, DateTime.Now);
                    yield break;
                }
                long   fileSize    = Convert.ToInt64(strLength);
                string strDateTime = request.GetResponseHeader("Last-Modified");
                if (string.IsNullOrEmpty(strDateTime))
                {
                    onGetRemoteFileInfo(fileName, "GetRemoteFileInfo - can not get Last-Modified", 0, DateTime.Now);
                    yield break;
                }
                DateTime lastModified = DateTime.Parse(strDateTime);
                onGetRemoteFileInfo(fileName, null, fileSize, lastModified);
            }
        }
        public IEnumerator CheckServerSupportPartialContent(string _url, Action <bool> _resultAct, Action <string> _errorAct = null)
        {
            using (UnityWebRequest www = UnityWebRequest.Head(_url))
            {
                yield return(www.Send());

                while (!www.isDone)
                {
                    yield return(null);
                }

                if (www.isNetworkError || www.isHttpError)
                {
                    if (_errorAct != null)
                    {
                        _errorAct(www.error);
                    }

                    _resultAct(false);
                }
                else
                {
                    _resultAct(www.GetResponseHeaders().ContainsKey("Accept-Ranges"));
                }
            }
        }
Пример #15
0
        public static void OpenWebUrl(string onlineUrl, IPackageVersion version, ApplicationProxy applicationProxy, string analyticsEvent, Action errorCallback)
        {
            var request = UnityWebRequest.Head(onlineUrl);

            try
            {
                var operation = request.SendWebRequest();
                operation.completed += (op) =>
                {
                    if (request.responseCode >= 200 && request.responseCode < 300)
                    {
                        applicationProxy.OpenURL(onlineUrl);
                        PackageManagerWindowAnalytics.SendEvent($"{analyticsEvent}ValidUrl", version?.uniqueId);
                    }
                    else
                    {
                        errorCallback?.Invoke();
                    }
                };
            }
            catch (InvalidOperationException e)
            {
                if (e.Message != "Insecure connection not allowed")
                {
                    throw e;
                }
            }
        }
Пример #16
0
        private static void ViewUrl(Func <string> getUrl, Func <string> getOfflineUrl, string messageOnNotFound)
        {
            if (Application.internetReachability != NetworkReachability.NotReachable)
            {
                var onlineUrl = getUrl();
                var request   = UnityWebRequest.Head(onlineUrl);
                var operation = request.SendWebRequest();
                operation.completed += (op) =>
                {
                    if (request.responseCode != 404)
                    {
                        Application.OpenURL(onlineUrl);
                    }
                    else
                    {
                        ViewOfflineUrl(getOfflineUrl, messageOnNotFound);
                    }
                };
            }
            else

            {
                ViewOfflineUrl(getOfflineUrl, messageOnNotFound);
            }
        }
Пример #17
0
 /// <summary>
 /// Download the header of the specified asset
 /// </summary>
 private void LoadHeader(string fileName)
 {
     Log($"Downloading header asset {fileName}...");
     www = UnityWebRequest.Head($"{baseUrl}/{fileName}");
     www.SendWebRequest();
     state = State.HeaderDownloading;
 }
Пример #18
0
        public IEnumerator HttpHead(string url, System.Action <Response> callback)
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Head(url))
            {
                yield return(webRequest.SendWebRequest());

                if (webRequest.isNetworkError)
                {
                    callback(new Response {
                        StatusCode = webRequest.responseCode,
                        Error      = webRequest.error,
                    });
                }

                if (webRequest.isDone)
                {
                    var responseHeaders = webRequest.GetResponseHeaders();
                    callback(new Response {
                        StatusCode = webRequest.responseCode,
                        Error      = webRequest.error,
                        Headers    = responseHeaders
                    });
                }
            }
        }
        private static IEnumerator DownloadAssetBundle(Uri uri,
                                                       IObserver <AssetBundle> observer,
                                                       CancellationToken cancellationToken)
        {
            UnityWebRequest headReq = UnityWebRequest.Head(uri);

            yield return(headReq.SendWebRequest());

            Dictionary <string, string> headers = headReq.GetResponseHeaders();
            string          lastModification    = headReq.GetResponseHeader("Last-Modified");
            uint            version             = (lastModification == null) ? 0 : (uint)lastModification.GetHashCode();
            UnityWebRequest request             = UnityWebRequestAssetBundle.GetAssetBundle(uri, version, 0);

            request.SendWebRequest();

            while (!request.isDone && !cancellationToken.IsCancellationRequested)
            {
                yield return(null);
            }

            if (cancellationToken.IsCancellationRequested)
            {
                yield break;
            }

            if (request.error != null)
            {
                observer.OnError(new Exception(request.error));
            }
            else
            {
                observer.OnNext(DownloadHandlerAssetBundle.GetContent(request));
                observer.OnCompleted();
            }
        }
Пример #20
0
    public IEnumerator HeadCoroutine(string url,
                                     float timeOut,
                                     Action <string> onFinish           = null,
                                     Action <float> onUploadDownloading = null)
    {
#if UNITY_EDITOR
        if (Tracking)
        {
            PrintTrack(MethodBase.GetCurrentMethod().Name);
            PrintTrack("url: " + url);
        }
#endif

#if VIRTUAL_SERVER
        if (VirtualServer.Instance.IsContainUrl(url))
        {
            if (onFinish != null)
            {
                onFinish(VirtualServer.Instance.Send(url));
            }
            yield break;
        }
#endif

        UnityWebRequest www = UnityWebRequest.Head(url);
        yield return(WebRequestCoroutineCore(www, timeOut, onFinish, onUploadDownloading));
    }
Пример #21
0
    IEnumerator GetFileSize(string url, UnityAction <int> size)
    {
        UnityWebRequest uwr = UnityWebRequest.Head(url);

        yield return(uwr.SendWebRequest());

        size.Invoke(int.Parse(uwr.GetResponseHeader("Content-Length")));
    }
Пример #22
0
 /// <summary>
 /// 发送GET请求
 /// </summary>
 /// <param name="timeout">超时:从请求开始计时</param>
 public void SendRequest(int timeout = 0)
 {
     if (_webRequest == null)
     {
         _webRequest         = UnityWebRequest.Head(URL);
         _webRequest.timeout = timeout;
         _webRequest.SendWebRequest();
     }
 }
Пример #23
0
        private static IEnumerator _DownloadFile(string url, string savePath,
                                                 OnRequestSuccess onDownloadStart,
                                                 OnRequestSuccess onFinish,
                                                 OnRequestError onError,
                                                 OnRequestProgress onProgress)
        {
            var headRequest = UnityWebRequest.Head(url);

            yield return(headRequest.SendWebRequest());

            var totalSize = long.Parse(headRequest.GetResponseHeader("Content-Length"));
            var fileInfo  = new FileInfo(savePath);

            if (fileInfo.Exists && fileInfo.Length == totalSize)
            {
                onFinish?.Invoke(headRequest);
            }
            else
            {
                using (var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET))
                {
                    var handler = new DownloadHandlerFileRange(savePath, request);
                    request.downloadHandler = handler;
                    onDownloadStart?.Invoke(request);

                    var asyncOp = request.SendWebRequest();
                    while (!asyncOp.isDone)
                    {
                        yield return(null);

                        onProgress?.Invoke(asyncOp);
                    }

                    if (request.isNetworkError || request.isHttpError)
                    {
                        handler.Close();
                        if (onError != null)
                        {
                            Debug.LogWarningFormat("SendRequest Failed:\nresponseCode :{0}\nerror :{1}\nurl:{2}",
                                                   request.responseCode, request.error, request.url);
                            onError(request);
                        }
                        else
                        {
                            Debug.LogErrorFormat("SendRequest Failed:\nresponseCode :{0}\nerror :{1}\nurl:{2}",
                                                 request.responseCode, request.error, request.url);
                        }
                    }
                    else
                    {
                        Debug.LogFormat("Finish UnityWebRequest: {0}\nresponseCode :{1}", request.url,
                                        request.responseCode);
                        onFinish?.Invoke(request);
                    }
                }
            }
        }
 public static IObservable <Unit> Head(string url, Dictionary <string, string> requestHeaderMap = null, IProgress <float> progress = null)
 {
     return(Request(
                UnityWebRequest.Head(url),
                requestHeaderMap,
                (DownloadHandler _) => Unit.Default,
                progress
                ));
 }
        //checks for the most recent version available online
        internal void GetLatestETag(Action <AsyncOperation> onGet)
        {
            var request = UnityWebRequest.Head(k_PackageUri);

            request.suppressErrorsToConsole = true;
            var operation = request.SendWebRequest();

            operation.completed += onGet;
        }
Пример #26
0
    void test()
    {
        var hww = UnityWebRequest.Head(testUrl as string);

        hww.Send();
        if (!hww.isDone)
        {
            return;
        }
    }
Пример #27
0
        /// <summary>
        /// Setup request.
        /// </summary>
        public void Setup()
        {
            // Determine which request to use.
            switch (requestInfo.RequestType)
            {
            case Netko.RequestType.Get:
                UnityRequest = UnityWebRequest.Get(requestInfo.Url.GetUriEscaped());
                break;

            case Netko.RequestType.Post:
                UnityRequest = UnityWebRequest.Post(requestInfo.Url.GetUriEscaped(), requestInfo.Form);
                if (requestInfo.UploadHandler != null)
                {
                    UnityRequest.uploadHandler = requestInfo.UploadHandler;
                }
                break;

            case Netko.RequestType.Delete:
                UnityRequest = UnityWebRequest.Delete(requestInfo.Url.GetUriEscaped());
                break;

            case Netko.RequestType.Put:
                UnityRequest = UnityWebRequest.Put(requestInfo.Url.GetUriEscaped(), requestInfo.PutData);
                break;

            case Netko.RequestType.Head:
                UnityRequest = UnityWebRequest.Head(requestInfo.Url.GetUriEscaped());
                break;

            case Netko.RequestType.Audio:
                UnityRequest = UnityWebRequest.GetAudioClip(requestInfo.Url.GetUriEscaped(), requestInfo.AudioType);
                break;

            case Netko.RequestType.AudioStream:
                AudioRequest = new AudioStreamRequest(requestInfo.Url.GetUriEscaped(true));
                break;

            case Netko.RequestType.Texture:
                UnityRequest = UnityWebRequest.GetTexture(
                    requestInfo.Url.GetUriEscaped(), requestInfo.TextureNonReadable
                    );
                break;

            case Netko.RequestType.AssetBundle:
                UnityRequest = UnityWebRequest.GetAssetBundle(
                    requestInfo.Url.GetUriEscaped(), requestInfo.AssetBundleVersion, requestInfo.AssetBundleCRC
                    );
                break;
            }

            // Initialize variables
            SetError(null);
            isProcessing = false;
            TimeOutTime  = requestInfo.TimeOut;
        }
Пример #28
0
 public void Start()
 {
     request = UnityWebRequest.Head(url);
     #if UNITY_2017_1_OR_NEWER
     request.SendWebRequest();
     #else
     request.Send();
     #endif
     progress = 0;
     isDone   = false;
 }
Пример #29
0
        IEnumerator Start()
        {
            // Keep network from sleeping.
            while (true)
            {
                UnityWebRequest request = UnityWebRequest.Head("http://www.example.com");
                yield return(request.SendWebRequest());

                yield return(new WaitForSeconds(1f));
            }
        }
Пример #30
0
        private System.Collections.IEnumerator SendHeadReqTo(string ipOrUrl)
        {
            Response <UnityWebRequest> resp = new Response <UnityWebRequest>();

            resp.onError = null;
            if (!ipOrUrl.StartsWith("http"))
            {
                ipOrUrl = "https://" + ipOrUrl;
            }
            yield return(UnityWebRequest.Head(ipOrUrl).SendWebRequestV2(resp));
        }