/// <summary> /// 请求验证码 /// </summary> /// <param name="req"></param> /// <param name="buildContext"></param> public async Task <bool> VerificationCode(WWWForm www) { string url = @"http://test.poliq.net:8080/sendLoginSms"; string msg = null; string code = null; UnityWebRequest request = await HttpPost(url, www); Debug.Log(request.responseCode); switch (request.responseCode) { case 200: Debug.Log(request.downloadHandler.text); return(true); case 500: msg = HttpUtility.UrlDecode(request.GetResponseHeader(user_msg), Encoding.UTF8); code = request.GetResponseHeader(user_code); UIManager.Instance.SystemDialog(msg + " " + code, 500); return(false); default: return(false); } }
private IEnumerator followRedirects(string url, ReadResponse response) { UnityWebRequest request = UnityWebRequest.Get(url); request.redirectLimit = 0; yield return(request.SendWebRequest()); while (!request.isDone) { yield return(null); } if (!string.IsNullOrEmpty(request.GetResponseHeader("LOCATION"))) { yield return(followRedirects(request.GetResponseHeader("LOCATION"), response)); } else if (request.isHttpError || request.isNetworkError) { Log.LogErrorFormatted(this, "GCS request to {0} failed with error: {1}", request.url, request.error); response.HasError = true; response.ErrorCode = request.responseCode; } else if (request.responseCode == 200) { response.Data = request.downloadHandler.text; } else { response.HasError = true; response.ErrorCode = request.responseCode; Log.LogErrorFormatted(this, "GCS request to {0} failed with status: {1} and body: {2} and error: {3}", request.url, request.responseCode, request.downloadHandler.text, request.error); } }
static IEnumerator GetNewSessionCoroutine(string locationID) { //adding parameters for the POST request WWWForm form = new WWWForm(); form.AddField("locationid", locationID); //creating request UnityWebRequest request = UnityWebRequest.Post(URL + "/getnewsession", form); //sending request and waiting for response yield return(request.SendWebRequest()); if (request.isHttpError || request.isNetworkError) { //error handling Debug.Log("request ended with an error: " + request.error); Debug.Log(request.downloadHandler.text); } else { //response ended succesfully var sessionid = request.GetResponseHeader("sessionid"); var userid = request.GetResponseHeader("userid"); Debug.LogFormat("Found session with ID {0} for user {1}", sessionid, userid); } }
/// <summary> /// 获取个人信息 /// </summary> /// <returns></returns> public async Task <bool> GetPersonInformation(string id) { string url = @"http://test.poliq.net:8080/user/" + id; string msg = null; string code = null; UnityWebRequest request = await HttpGet(url); Debug.Log(request.responseCode); switch (request.responseCode) { case 200: Debug.Log(request.downloadHandler.text); UserInformation.Instance.Init(request.downloadHandler.text); return(true); case 500: msg = HttpUtility.UrlDecode(request.GetResponseHeader(user_msg), Encoding.UTF8); code = request.GetResponseHeader(user_code); UIManager.Instance.SystemDialog(msg + " " + code, 500); return(false); default: return(false); } }
public void GetAuthTokenHandler(UnityWebRequest req) { if (req.GetResponseHeader("X-Subject-Token") != null) { authToken = req.GetResponseHeader("X-Subject-Token"); } }
/// <summary> /// 修改个人信息 /// </summary> public async Task <bool> ChangeInforMation(WWWForm www) { string url = @"http://test.poliq.net:8080/user/profile"; string msg = null; string code = null; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add(user_token, PlayerPrefs.GetString("TOKEN")); UnityWebRequest request = await HttpPost(url, www, dic); Debug.Log(request.responseCode); switch (request.responseCode) { case 200: Debug.Log(request.downloadHandler.text); return(true); case 500: msg = HttpUtility.UrlDecode(request.GetResponseHeader(user_msg), Encoding.UTF8); code = request.GetResponseHeader(user_code); UIManager.Instance.SystemDialog(msg + " " + code, 500); return(false); default: UIManager.Instance.SystemDialog("发生未知错误", 500); return(false); } }
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()); }
/// <summary> /// 取消关注 /// </summary> /// <returns></returns> public async Task <bool> CancelFollow(WWWForm www) { string url = @"http://test.poliq.net:8080/user/undoFollowing"; string msg = null; string code = null; UnityWebRequest request = await HttpPost(url, www); Debug.Log("responseCode:" + request.responseCode); switch (request.responseCode) { case 200: Debug.Log(request.downloadHandler.text); return(true); case 500: try { Debug.Log(500); msg = HttpUtility.UrlDecode(request.GetResponseHeader(user_msg), Encoding.UTF8); code = request.GetResponseHeader(user_code); UIManager.Instance.SystemDialog(msg + " " + code, 500); } catch (Exception e) { Debug.Log("异常"); } return(false); default: UIManager.Instance.SystemDialog("未知错误", 500); return(false); } }
/// <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); } }
/// <summary> /// 获取关注列表 id 页码pageNo pageSize:"2" /// </summary> /// <param name="userid"></param> /// <returns></returns> public async Task <bool> GetFollowingList(string userid, string pageNo, string pageSize) { string url = @"http://test.poliq.net:8080/user/getFollowingList/" + userid + "?" + "pageNo=" + pageNo + "&" + "pageSize=" + pageSize; Debug.Log(url); string msg = null; string code = null; UnityWebRequest request = await HttpGet(url); Debug.Log(request.responseCode); GameFacade.Instance.text.text = request.responseCode.ToString(); Debug.Log(request.responseCode); switch (request.responseCode) { case 200: Debug.Log(request.downloadHandler.text); DataManager.Instance.SetfollowingListJson(request.downloadHandler.text); GameFacade.Instance.text.text = DataManager.Instance.followingList.Count.ToString(); return(true); case 500: msg = HttpUtility.UrlDecode(request.GetResponseHeader(user_msg), Encoding.UTF8); code = request.GetResponseHeader(user_code); UIManager.Instance.SystemDialog(msg + " " + code, 500); return(false); default: return(false); } }
public IEnumerator getTime() { UnityWebRequest www = UnityWebRequest.Get("https://www.microsoft.com"); yield return(www.SendWebRequest()); if (www.isNetworkError) { Debug.Log(www.error); } else { if (www.isHttpError) { www = UnityWebRequest.Get("https://www.google.com"); yield return(www.SendWebRequest()); if (www.isHttpError) { Debug.Log(www.error); } else { string date = www.GetResponseHeader("date"); yield return(new WaitForSecondsRealtime(0.1f)); datetime = DateTime.ParseExact(date, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal); Debug.Log(datetime); string[] words_ = datetime.ToString().Split(' '); //timerTestLabel.text = www.text; //setting current time _currentDate = words_[0]; _currentTime = words_[1]; } } else { string date = www.GetResponseHeader("date"); yield return(new WaitForSecondsRealtime(0.1f)); datetime = DateTime.ParseExact(date, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal); string[] _words = datetime.ToString().Split(' '); //timerTestLabel.text = www.text; //setting current time _currentDate = _words[0]; _currentTime = _words[1]; } } }
private static HttpContent GenerateHttpContentFromUnityWebRequest(UnityWebRequest unityRequest) { ByteArrayContent arrayContent = new ByteArrayContent(unityRequest.downloadHandler.data); Debug.Log($"ResponseHeader: {unityRequest.GetResponseHeader("Content-Type")}"); arrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse(unityRequest.GetResponseHeader("Content-Type")); return(arrayContent); }
public MyHTTPResponse(UnityWebRequest webReq) { status = (HttpStatusCode)webReq.responseCode; contentType = webReq.GetResponseHeader("Content-type"); etag = webReq.GetResponseHeader("Etag"); lastModified = Convert.ToDateTime(webReq.GetResponseHeader("Last-Modified")); content = webReq.downloadHandler.data; }
private IEnumerator SendDownloader(Action <FDownloader> callBack) { using (var www = new UnityWebRequest(mDownloader.URL, mDownloader.Method)) { mUnityWeb = www; mDownloader.CreateStream(); www.downloadHandler = new MyUnityDownloadHandler(mDownloader); www.SetRequestHeader("Content-Type", string.IsNullOrEmpty(mDownloader.ContentType) ? "application/x-www-form-urlencoded" : mDownloader.ContentType); long startIndex = mDownloader.GetBreakStreamCount(); if (startIndex > 0) { www.SetRequestHeader("Range", "bytes=" + startIndex + "-"); } www.SendWebRequest(); yield return(0); if (mDownloader.TotalLength <= 0) { string lengthstr = www.GetResponseHeader("Content-Length"); while (string.IsNullOrEmpty(lengthstr) && !www.isDone && !www.isHttpError && !www.isNetworkError) { lengthstr = www.GetResponseHeader("Content-Length"); yield return(0); } if (!string.IsNullOrEmpty(lengthstr)) { mDownloader.TotalLength = long.Parse(lengthstr) + startIndex; } } //int index = 0; while (!www.isDone && !www.isHttpError && !www.isNetworkError) { //if (www.downloadHandler != null && www.downloadHandler.data != null && www.downloadHandler.data.Length > index) //{ // var len = www.downloadHandler.data.Length - index; // mDownloader.WriteStream(www.downloadHandler.data, index, len); // index += len; //} yield return(new WaitForSeconds(1.0f)); } if (!string.IsNullOrEmpty(www.error)) { mDownloader.ExceptionCode((int)www.responseCode); mDownloader.SetError(www.error); } else { mDownloader.HandleStream(); } mUnityWeb = null; callBack(mDownloader); } }
public IEnumerator GetTime(Action <bool> callBack = null, Action callBack2 = null) { UnityWebRequest www = UnityWebRequest.Get("https://www.microsoft.com"); yield return(www.SendWebRequest()); if (www.isNetworkError) { //Log.Info("TIME" + www.error); check = false; } else { if (www.isHttpError) { www = UnityWebRequest.Get("https://www.google.com"); yield return(www.SendWebRequest()); if (www.isHttpError) { // Log.Info(www.error); check = false; } else { string date = www.GetResponseHeader("date"); yield return(new WaitForSecondsRealtime(0.1f)); currentTime = DateTime.ParseExact(date, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal); check = true; } } else { string date = www.GetResponseHeader("date"); yield return(new WaitForSecondsRealtime(0.1f)); currentTime = DateTime.ParseExact(date, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal); check = true; } } callBack?.Invoke(check); callBack2?.Invoke(); }
public int ProtocolVersion() { // error type checking if (type == ResponseTypes.ERR) { return(0); } string strProto = request.GetResponseHeader("X-MDM-Protocol-Version"); int intProto = 0; int.TryParse(strProto, out intProto); return(intProto); }
private IEnumerator SendTusRequest() { ReadBytes(); m_uploadRequest = UnityWebRequest.Put(m_url, bytes); SetupTusRequest(m_uploadRequest); m_uploadRequest.method = "PATCH"; m_uploadRequest.SetRequestHeader("Upload-Offset", m_lastByteUploaded.ToString()); m_uploadRequest.SetRequestHeader("Content-Type", "application/offset+octet-stream"); m_isUploading = true; yield return(VimeoApi.SendRequest(m_uploadRequest)); if (m_uploadRequest.isNetworkError || m_uploadRequest.isHttpError) { UploadError(m_uploadRequest.responseCode + ": " + m_uploadRequest.error); } else { m_isUploading = false; m_isFinishedUploading = true; if (OnChunkUploadComplete != null) { OnChunkUploadComplete(this, m_uploadRequest.GetResponseHeader("Upload-Offset")); } } DisposeBytes(); }
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"; } } }
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(); } }
private void OnUrlShorteningComplete(string shortUrl) { ResultUrl = activeRequest.GetResponseHeader("Location"); Status = PublisherStatus.Done; activeRequest = null; mockThread = null; }
IEnumerator Send(string url, string json, Action <bool, string> callback) { string uId = SystemInfo.deviceUniqueIdentifier; UnityWebRequest webRequest = UnityWebRequest.Put(url, json); webRequest.SetRequestHeader("TLT", uId + "." + Helper.Tlt(SystemInfo.deviceUniqueIdentifier, json)); yield return(webRequest.Send()); bool responseStatus = false; if (!webRequest.isError && webRequest.responseCode == 200) { string responseTlt = webRequest.GetResponseHeader("TLT"); if (responseTlt != null) { string[] TltPart = responseTlt.Split("."[0]); if (TltPart.Length == 2) { if (TltPart[1] == Helper.Tlt(uId, webRequest.downloadHandler.text)) { responseStatus = true; } } } } callback(responseStatus, webRequest.downloadHandler.text); }
private static List <string> GetResponseHeaders(UnityWebRequest self, string headerName) { List <string> cookies = new List <string>(); cookies.Add(self.GetResponseHeader(headerName)); return(cookies); }
private static void FillRequestResult(UnityWebRequest request, ref OnlineTimeResult result) { if (!string.IsNullOrEmpty(request.error)) { result.SetError(request.error, request.responseCode); } else { var dateHeader = request.GetResponseHeader("Date"); if (!string.IsNullOrEmpty(dateHeader)) { DateTime serverTime; var success = TryGetDate(dateHeader, out serverTime); if (success) { var onlineTimeUtc = serverTime.ToUniversalTime(); var onlineSecondsUtc = onlineTimeUtc.Ticks / (double)TimeSpan.TicksPerSecond; result.SetTime(onlineSecondsUtc, onlineTimeUtc); } else { result.SetError("Couldn't parse 'Date' response header value\n " + dateHeader, request.responseCode); } } else { result.SetError("Couldn't find 'Date' response header value!", request.responseCode); } } if (!result.success) { Debug.Log(FinalLogPrefix + "Online Time Retrieve error:\n" + result); } }
/// <summary> /// Fetches the lyrics of the given song online asynchronously and, if they're found, /// populates the given list. /// </summary> public static IEnumerator GetOnlineLyrics(IBeatmapLevel level, List <Subtitle> subtitles) { // Perform request UnityWebRequest req = UnityWebRequest.Get($"https://beatsinger.herokuapp.com/{level.GetLyricsHash()}"); yield return(req.SendWebRequest()); if (req.isNetworkError || req.isHttpError) { Debug.Log(req.error); } else if (req.responseCode == 200) { // Request done, process result try { if (req.GetResponseHeader("Content-Type") == "application/json") { PopulateFromJson(req.downloadHandler.text, subtitles); } else { using (StringReader reader = new StringReader(req.downloadHandler.text)) PopulateFromSrt(reader, subtitles); } } catch (Exception e) { Debug.LogException(e); } } req.Dispose(); }
private void HandleStatusRequestCompleted(AsyncOperation asyncOperation) { // The upload was completed, no further action is necessary. if (statusRequest.responseCode == 200 || statusRequest.responseCode == 201) { CompleteRequest(); } // The upload session has expired and the upload needs to be restarted from the beginning. else if (statusRequest.responseCode == 404) { ResumeOffset = 0; ResumeUpload(); } // The upload wasn't completed and should be resumed. else if (statusRequest.responseCode == 308) { var rangeHeader = statusRequest.GetResponseHeader("Range"); Debug.Assert(!string.IsNullOrEmpty(rangeHeader) && rangeHeader.Contains("-")); ResumeOffset = int.Parse(rangeHeader.Split('-')[1]) + 1; ResumeUpload(); } // Unexpected response. else { AppendError(string.Format("Failed to resume upload. HTTP error: {0}", statusRequest.error)); CompleteRequest(); } statusRequest.Dispose(); }
IEnumerator AttemptCreation(string request, Action <string> callBack, Action <string> errorCallBack) { UnityWebRequest r = UnityWebRequest.Get(URL_TryCreate + UnityWebRequest.EscapeURL(request)); yield return(r.SendWebRequest()); if (r.error != null) { Logger.Log("DB request failed: " + r.error, Category.DatabaseAPI); errorCallBack.Invoke(r.error); } else { var apiResponse = JsonUtility.FromJson <ApiResponse>(r.downloadHandler.text); if (apiResponse.errorCode != 0) { errorCallBack.Invoke(apiResponse.errorMsg); } else { string s = r.GetResponseHeader("set-cookie"); sessionCookie = s.Split(';')[0]; callBack.Invoke(apiResponse.message); } } }
IEnumerator TryHubLogin(HubLoginReq loginRequest) { var requestData = JsonUtility.ToJson(loginRequest); UnityWebRequest r = UnityWebRequest.Get(hubLogin + UnityWebRequest.EscapeURL(requestData)); yield return(r.SendWebRequest()); if (r.error != null) { Logger.Log("Hub Login request failed: " + r.error, Category.DatabaseAPI); yield break; } else { var response = JsonUtility.FromJson <ApiResponse>(r.downloadHandler.text); if (response.errorCode == 0) { string s = r.GetResponseHeader("set-cookie"); hubCookie = s.Split(';') [0]; Logger.Log("Hub connected successfully", Category.DatabaseAPI); r = UnityWebRequest.Get("http://ipinfo.io/ip"); yield return(r.SendWebRequest()); publicIP = Regex.Replace(r.downloadHandler.text, @"\t|\n|\r", ""); connectedToHub = true; } else { Logger.Log("Hub Login request failed: " + response.errorMsg, Category.DatabaseAPI); } } }
IEnumerator GetRequest(string uri) { while (true) { using (UnityWebRequest webRequest = UnityWebRequest.Get(uri)) { // Request and wait for the desired page. webRequest.GetRequestHeader("application/json"); webRequest.GetResponseHeader("application/json"); yield return(webRequest.SendWebRequest()); string[] pages = uri.Split('/'); int page = pages.Length - 1; if (webRequest.isNetworkError) { Debug.Log(pages[page] + ": Error: " + webRequest.error); } else { Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text); var data = webRequest.downloadHandler.text; cacheData = JsonConvert.DeserializeObject <List <PatientData> >(data); //Debug.Log(output.Name); } } yield return(new WaitForSeconds(5)); Debug.Log("List size is " + cacheData.Count); } }
private static async Task <Response> DevicePortalAuthorizationAsync(DeviceInfo targetDevice) { UnityWebRequest webRequest = UnityWebRequest.Get(FinalizeUrl(targetDevice.IP)); webRequest.timeout = 5; webRequest.SetRequestHeader("Authorization", targetDevice.Authorization["Authorization"]); await webRequest.SendWebRequest(); if (webRequest.isNetworkError || webRequest.isHttpError) { if (webRequest.responseCode == 401) { return(new Response(false, "Invalid Credentials", null, webRequest.responseCode)); } if (webRequest.GetResponseHeaders() == null) { return(new Response(false, "Device Not Found | No Response Headers", null, webRequest.responseCode)); } string responseHeaders = webRequest.GetResponseHeaders().Aggregate(string.Empty, (current, header) => $"\n{header.Key}: {header.Value}"); string downloadHandlerText = webRequest.downloadHandler?.text; Debug.LogError($"REST Auth Error: {webRequest.responseCode}\n{downloadHandlerText}{responseHeaders}"); return(new Response(false, $"{downloadHandlerText}", webRequest.downloadHandler?.data, webRequest.responseCode)); } return(new Response(true, () => webRequest.GetResponseHeader("Set-Cookie"), () => webRequest.downloadHandler?.data, webRequest.responseCode)); }
/// <summary> /// Callback, invoked when the data property is accessed. /// </summary> protected override byte[] GetData() { if (!isDone) { Logger.Error("{0}Downloading is not completed : {1}", kLog, m_WebRequest.url); throw new InvalidOperationException("Downloading is not completed. " + m_WebRequest.url); } else if (m_Buffer == null) { // Etag cache hit! if (m_WebRequest.responseCode == 304) { Logger.Debug("<color=green>{0}Etag cache hit : {1}</color>", kLog, m_WebRequest.url); m_Buffer = LoadCache(m_WebRequest.url); } // Download is completed successfully. else if (m_WebRequest.responseCode == 200) { Logger.Debug("<color=green>{0}Download is completed successfully : {1}</color>", kLog, m_WebRequest.url); m_Buffer = m_Stream.GetBuffer(); SaveCache(m_WebRequest.url, m_WebRequest.GetResponseHeader("Etag"), m_Buffer); } } if (m_Stream != null) { m_Stream.Dispose(); m_Stream = null; } return(m_Buffer); }