public IEnumerator GetImage(System.Action<Image> callback, System.Action<string> errorCallback) { if (imageList.Images.Count == 0) { // no images, get new yield return StartCoroutine(GetImages(errorCallback)); } if (imageList.Images.Count == 0) { yield break; } int index = Random.Range(0, imageList.Images.Count - 1); Image i = imageList.Images[index]; HTTPRequest req = new HTTPRequest(new System.Uri(i.Url)); req.Send(); yield return StartCoroutine(req); if(req.Response==null || !req.Response.IsSuccess) { errorCallback("Get Image Error"); yield break; } imageList.Images.RemoveAt(index); i.Tex = req.Response.DataAsTexture2D; callback(i); yield return null; }
private void Start() { HTTPRequest request = new HTTPRequest(new Uri(APIUrl.UrlUserId + "/" + PlayerPrefs.GetString("UserId") + "?access_token=" + PlayerPrefs.GetString("token")), HTTPMethods.Get, OnRequestFinished); // Debug.Log(APIUrl.UrlUserId + "/" + PlayerPrefs.GetString("UserId") + "?access_token=" + PlayerPrefs.GetString("token")); // request.AddField("id", PlayerPrefs.GetString("UserId")); request.Send(); }
public void sendAction() { GetComponent<Animator>().Play("Click"); if (buttonType == FLOOR_BUTTON_TYPE.YES || buttonType == FLOOR_BUTTON_TYPE.NO) { GameObject.Find("Debug Text").GetComponent<Text>().text += "Setting Position \n"; HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/action"), HTTPMethods.Put, actionSentCallback); JSONClass data = new JSONClass(); data["value"] = ((int)buttonType).ToString(); request.AddHeader("Content-Type", "application/json"); //request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012"); request.RawData = Encoding.UTF8.GetBytes(data.ToString()); request.Send(); } else { HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/dlswitch"), HTTPMethods.Put, actionSentCallback); JSONClass data = new JSONClass(); data["value"] = (dlSwitch).ToString(); request.AddHeader("Content-Type", "application/json"); //request.AddHeader("X-M2X-KEY", "9fc7996ea7f03fccc6ef3978f2a4d012"); request.RawData = Encoding.UTF8.GetBytes(data.ToString()); request.Send(); } }
void doAuthentication(string username, string password) { // if there is no token stored, negotiate a new one HTTPRequest req = new HTTPRequest (new System.Uri (Properties.API + "/authenticate"), HTTPMethods.Post, onAuthenticationFinished); req.AddField ("username", username); req.AddField ("password", password); req.Send (); }
private void OnClick() { HTTPRequest request = new HTTPRequest(new Uri(APIUrl.UrlLogin), HTTPMethods.Post, OnRequestFinished); request.AddField("username", username.text); request.AddField("password", password.text); request.Send(); //SceneManager.LoadScene(1); }
// get game info from API void getGame() { // get all the games HTTPRequest request = new HTTPRequest(new System.Uri(Properties.API + "/game/" + _gameId), (HTTPRequest req, HTTPResponse res) => { // deserialize json GameModel games = JsonMapper.ToObject<GameModel> (res.DataAsText); // build scene buildScene(games); }); request.AddField ("token", PlayerPrefs.GetString ("token")); request.Send (); }
// create a new game public void createGame() { string challenger = PlayerPrefs.GetString("username"); string challenged = (challenger == "berni") ? "gemmins" : "berni"; Debug.Log (PlayerPrefs.GetString("token")); HTTPRequest request = new HTTPRequest (new System.Uri (Properties.API + "/game"), HTTPMethods.Post, (HTTPRequest req, HTTPResponse res) => { //TODO: jump to the new game }); request.AddField ("challenger", challenger); request.AddField ("challenged", challenged); request.AddField ("token", PlayerPrefs.GetString("token")); request.Send (); }
/// <summary> /// OSS Get /// </summary> /// <param name="url"></param> /// <param name="post"></param> /// <param name="OnRequestFinished"></param> /// <param name="token"></param> public static void OssGet(string url, KeyValuePair <string, string>[] post, OnRequestFinishedDelegate OnRequestFinished, string token = null) { BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(url), true, OnRequestFinished); request.Timeout = TimeSpan.FromMinutes(10); request.ConnectTimeout = TimeSpan.FromMinutes(5); if (post != null) { foreach (var item in post) { request.SetHeader(item.Key, item.Value); } } request.Send(); }
protected override void SendImpl(string json) { var request = new HTTPRequest(Connection.BuildUri(RequestTypes.Send, this), HTTPMethods.Post, true, true, OnSendRequestFinished); request.FormUsage = Forms.HTTPFormUsage.UrlEncoded; request.AddField("data", json); Connection.PrepareRequest(request, RequestTypes.Send); // Set a lower priority then the default. This way requests that are sent out alonside with SignalR sent requests can be processed sooner. request.Priority = -1; request.Send(); sendRequestQueue.Add(request); }
/// <summary> /// Polling transport specific connection logic. It's a regular GET request to the /connect path. /// </summary> public override void Connect() { HTTPManager.Logger.Information("Transport - " + this.Name, "Sending Open Request"); // Skip the Connecting state if we are reconnecting. If the connect succeeds, we will set the Started state directly if (this.State != TransportStates.Reconnecting) this.State = TransportStates.Connecting; RequestTypes requestType = this.State == TransportStates.Reconnecting ? RequestTypes.Reconnect : RequestTypes.Connect; var request = new HTTPRequest(Connection.BuildUri(requestType, this), HTTPMethods.Get, true, true, OnConnectRequestFinished); Connection.PrepareRequest(request, requestType); request.Send(); }
public IEnumerator LogIn(string user, string pass){ string loginURI = "http://nebinstower.cloudapp.net:5000/login/"; string jsonString = "{\"username\": \"" + user + "\", \"password\": \"" + pass + "\"}"; HTTPRequest request = new HTTPRequest (new System.Uri (loginURI), HTTPMethods.Post); request.RawData = Encoding.UTF8.GetBytes(jsonString); request.AddHeader ("Content-Type", "application/json"); request.Send(); yield return StartCoroutine(request); Debug.Log (request.Response.DataAsText); if (request.Response.StatusCode == 200) { Debug.Log ("success"); JObject o = JObject.Parse (request.Response.DataAsText); PlayerPrefs.SetString ("token", o ["token"].Value<string> ()); PlayerPrefs.SetString ("username", user); errorText.text = ""; loginComplete (); } else if (request.Response.StatusCode == 404) { string registerURI = "http://nebinstower.cloudapp.net:5000/register/"; request = new HTTPRequest (new System.Uri (registerURI), HTTPMethods.Post); request.RawData = Encoding.UTF8.GetBytes (jsonString); request.AddHeader ("Content-Type", "application/json"); request.Send (); yield return StartCoroutine (request); Debug.Log (request.Response.DataAsText); JObject o = JObject.Parse (request.Response.DataAsText); PlayerPrefs.SetString ("token", o ["token"].Value<string> ()); PlayerPrefs.SetString ("username", user); errorText.text = ""; loginComplete (); } else { errorText.text = request.Response.DataAsText; } }
public static Task <T> CreateTask <T>(HTTPRequest request, CancellationToken token, Action <HTTPRequest, HTTPResponse, TaskCompletionSource <T> > callback) { var tcs = new TaskCompletionSource <T>(); request.Callback = (req, resp) => callback(req, resp, tcs); if (token.CanBeCanceled) { token.Register((state) => (state as HTTPRequest)?.Abort(), request); } if (request.State == HTTPRequestStates.Initial) { request.Send(); } return(tcs.Task); }
private IEnumerator load(string url) { HTTPRequest request = new HTTPRequest(new Uri(url)); request.Send(); yield return StartCoroutine(request); if (request.State == HTTPRequestStates.Error) { Debug.LogError("Request Finished with Error! " + (request.Exception != null ? (request.Exception.Message + "\n" + request.Exception.StackTrace) : "No Exception")); } else { thumbnail.texture = request.Response.DataAsTexture2D; Color newColor = new Color(1, 1, 1, 1); thumbnail.color = newColor; } }
public IEnumerator GetConfig(System.Action<bool> callback, System.Action<bool> callback2, System.Action<string> errorCallback) { HTTPRequest req = new HTTPRequest(new System.Uri("http://one.digitnode.com/config/")); req.Send(); yield return StartCoroutine(req); if (req.Response == null || !req.Response.IsSuccess) { errorCallback("Get Config Error"); yield break; } string data = req.Response.DataAsText; config = JsonConvert.DeserializeObject<AppConfig>(data); IsConfiged = true; GoogleAds.GetInstance(); callback(false); callback2(true); yield return null; }
/// <summary> /// 加载版本文件 /// </summary> /// <param name="onComplete"></param> /// <param name="onError"></param> public void LoadVersion(Action onComplete, Action onError) { string url = GameConfig.HOST_RES() + GameConfig.LOCAL_HTTP_CONFIG_FILE + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(url), (req, resp) => { if (resp != null) { Loom.RunAsync(() => { m_httpConfig = JsonFx.Json.JsonReader.Deserialize <VersionBundleConfig>(resp.DataAsText); M_CacheHttpBundles(); string infoFilePath = PathUtils.MakeFilePath(GameConfig.LOCAL_DOWNLOAD_INFO_FILE, PathUtils.PathType.MobileDiskWrite); if (File.Exists(infoFilePath)) { using (FileStream infoStream = File.OpenRead(infoFilePath)) { if (infoStream != null) { byte[] index = new byte[infoStream.Length]; infoStream.Read(index, 0, index.Length); string content = System.Text.Encoding.Default.GetString(index); DownloadFileInfo downloadFileInfo = JsonFx.Json.JsonReader.Deserialize <DownloadFileInfo>(content); ResHelper.Instance().lastZipIndex = downloadFileInfo.totalSize; for (int i = 0; i < downloadFileInfo.ids.Length; i++) { ResHelper.Instance().downloadedFiles.Add(downloadFileInfo.ids[i], 1); } } } } if (GameConfig.useLocalRes) { m_version = new VersionConfig(); m_version.version = "0.0.0"; Loom.QueueOnMainThread(() => { if (onComplete != null) { onComplete(); } }); } else { url = GameConfig.HOST_RES_ZIP() + "zip/" + GameConfig.LOCAL_VERSION_FILE + "?t=" + TimeUtils.CurLocalTimeMilliSecond(); BestHTTP.HTTPRequest zipRequest = new BestHTTP.HTTPRequest(new Uri(url), (zipReq, zipResp) => { if (zipResp != null) { m_version = JsonFx.Json.JsonReader.Deserialize <VersionConfig>(zipResp.DataAsText); if (null != onComplete) { onComplete(); } } else { if (null != onError) { onError(); } } }); zipRequest.Send(); } }); } else { if (null != onError) { onError(); } } }); request.DisableCache = true; request.Send(); }
//异步HTTP public static void SendRequest(string url, string data, LuaFunction completeHandler) { //如果web页面是静态返回数据,请用HTTPMethods.Get var request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, resp) => { if (completeHandler != null) { completeHandler.call(req, resp); //req, resp 需要暴露给slua导出 } }); request.RawData = Encoding.UTF8.GetBytes(data); request.ConnectTimeout = TimeSpan.FromSeconds(3);//3秒超时 request.Send(); }
// https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API.htm#How-To-Delete-a-Target IEnumerator DeleteTarget() { Debug.Log("CustomMessage: DeleteTarget()"); // Setting up query. string requestPath = "/targets/" + currentImageData.UniqueTargetId; string serviceURI = url + requestPath; string httpAction = "DELETE"; string contentType = ""; string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime()); // Create ContentMD5. MD5 md5 = MD5.Create(); var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes("")); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < contentMD5bytes.Length; i++) { sb.Append(contentMD5bytes[i].ToString("x2")); } string contentMD5 = sb.ToString(); string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath); // Build signature. HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key)); byte[] sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign); MemoryStream stream = new MemoryStream(sha1Bytes); byte[] sha1Hash = sha1.ComputeHash(stream); string signature = System.Convert.ToBase64String(sha1Hash); Debug.Log("<color=green>Signature: " + signature + "</color>"); // Build Http Request. BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(serviceURI)); request.MethodType = BestHTTP.HTTPMethods.Delete; request.RawData = Encoding.UTF8.GetBytes(""); request.AddHeader("Authorization", string.Format("VWS {0}:{1}", access_key, signature)); request.AddHeader("Content-Type", contentType); request.AddHeader("Date", date); request.Send(); yield return(StartCoroutine(request)); switch (request.State) { case BestHTTP.HTTPRequestStates.Error: Debug.Log("request error: " + request.Exception.Message); string errorText = request.Exception.Message; PrintStatusText("Exception: " + errorText); editButton.interactable = true; break; case BestHTTP.HTTPRequestStates.Finished: // There is an error if (request.Response.StatusCode != 200) { Debug.Log("request error: " + request.Response.Message); string result_code = JsonUtility.FromJson <VWSResponse>(request.Response.DataAsText).result_code; // The target is still being processed in Vuforia API. if (result_code == "TargetStatusProcessing") { PrintStatusText("Error: Profile is still being processed in Vuforia!"); } else { PrintStatusText("Error: " + result_code); } editButton.interactable = true; } else { Debug.Log("request success"); PrintStatusText("Deleted!"); // We disable cloud tracking for x seconds. The reason why we do this is because it takes time for // Vuforia to actually delete the record. If we continue cloud tracking, it would retrack the record. DisableCloudTracking(2f); // To get all the tracked targets. For testing. // IEnumerable<Vuforia.ObjectTarget> obj = Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().GetObjectTargets(); // IEnumerator myEnum = obj.GetEnumerator(); // while(myEnum.MoveNext()){ // print(myEnum.Current); // } // Clear local copy. Vuforia.TrackerManager.Instance.GetTracker <Vuforia.ObjectTracker>().GetTargetFinder <Vuforia.ImageTargetFinder>().ClearTrackables(false); // Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().Stop(); // Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().StartRecognition(); // Close edit menu. ToggleEditMenu(); // Enable the upload button. This is needed because the tracker is disabled, and therefore, events are not being triggered // which in turn stops our handler from setting button states. uploadButton.interactable = true; } break; } // Enable buttons. deleteDeleteButton.interactable = true; putEditButton.interactable = true; }
public void InitDownloadHttp() { try { if (m_remoteLength > 0) { SendToLua(m_localLength, m_remoteLength); return; } string path = PathUtils.MakeFilePath("http_zip.zip", PathUtils.PathType.MobileDiskWrite); string url = GameConfig.HOST_RES() + "http_zip.zip"; FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); HTTPRequest http = new BestHTTP.HTTPRequest(new Uri(url), HTTPMethods.Head, (req, resp) => { if (resp == null) { stream.Dispose(); return; } if (resp.StatusCode == 416) { stream.Dispose(); return; } if (resp.HasHeaderWithValue("accept-ranges", "none")) { stream.Dispose(); return; } m_remoteLength = GetLength(resp); if (m_remoteLength <= 0) { stream.Dispose(); return; } m_localLength = stream.Length; SendToLua(m_localLength, m_remoteLength); if (m_localLength == m_remoteLength) { m_zipIsOk = true; m_downloadComplated = true; StartDecompress(); return; } else { stream.Close(); if (NetSpeed.GetCurrentNetType() != JzwlNetworkInfo.TYPE_MOBILE) { StartDownloadHttp(); } } }); http.DisableCache = true; http.Send(); } catch (Exception ex) { Debug.Log(ex.Message + "\n" + ex.StackTrace); } }
public void setPosition() { HTTPRequest request = new HTTPRequest(new Uri("http://run-west.att.io/d9576f027ee8f/6e9234f387c9/9c7023eee2b3b23/in/flow/position"), HTTPMethods.Put, setPositionFinished); JSONClass data = new JSONClass(); data["value"] = position.ToString(); request.AddHeader("Content-Type", "application/json"); request.RawData = Encoding.UTF8.GetBytes(data.ToString()); request.Send(); moveScreenTo(); }
public IEnumerator saveCharacters(){ Fighter f = new Fighter (); string saveURL = "http://nebinstower.cloudapp.net:5000/saveCharacters/"; string token = PlayerPrefs.GetString ("token"); string user = PlayerPrefs.GetString ("username"); string jsonString = "{\"username\": \"" + user + "\", \"token\": \"" + token + "\", \"savedata\": " + JsonConvert.SerializeObject (f) + "}"; HTTPRequest request = new HTTPRequest (new System.Uri (saveURL), HTTPMethods.Post); request.RawData = Encoding.UTF8.GetBytes (jsonString); request.AddHeader ("Content-Type", "application/json"); request.Send (); yield return StartCoroutine (request); Debug.Log (request.Response.DataAsText); }
public IEnumerator loadCharactersTest() { string loadURL = "http://nebinstower.cloudapp.net:5000/loadCharacters/"; string token = PlayerPrefs.GetString("token"); string user = PlayerPrefs.GetString("username"); string jsonString = "{\"username\": \"" + user + "\", \"token\": \"" + token + "\"}"; HTTPRequest request = new HTTPRequest(new System.Uri(loadURL), HTTPMethods.Post); request.RawData = Encoding.UTF8.GetBytes(jsonString); request.AddHeader("Content-Type", "application/json"); request.Send(); yield return StartCoroutine(request); Debug.Log(request.Response.DataAsText); SaveState f = JsonConvert.DeserializeObject<SaveState>(request.Response.DataAsText); GameObject.Find("LOADER").GetComponent<Loader>().saveState.GoldCount = f.GoldCount; Application.LoadLevel("main"); }
private void OnClick() { // Debug.Log(characterList.GetIndex(characterSelected.centeredObject.transform).ToString()); if (!confirmPassword.text.Equals(password.text)) { return; } HTTPRequest request = new HTTPRequest(new Uri(APIUrl.UrlSignup), HTTPMethods.Post, OnRequestFinished); request.AddField("username", username.text); request.AddField("password", password.text); request.AddField("score", "0"); request.AddField("email", username.text + "*****@*****.**"); int n = characterList.GetIndex(characterSelected.centeredObject.transform); request.AddField("characterId", characteritemlist[n].id); request.Send(); }
private void Start() { //lay character ve HTTPRequest request = new HTTPRequest(new Uri(APIUrl.UrlCharater), HTTPMethods.Get, OnCharacterFinished); request.Send(); username = GameObject.Find("usernameSignup").GetComponent<UIInput>(); password = GameObject.Find("passwordSignup").GetComponent<UIInput>(); confirmPassword = GameObject.Find("confirmPassword").GetComponent<UIInput>(); characterSelected = GameObject.Find("characterList").GetComponent<UICenterOnChild>(); characterList = GameObject.Find("characterList").GetComponent<UIGrid>(); }
public AssetBundleDownloadFromHttp(string assetBundleName, string url, int version, int crc, int level) : base(assetBundleName) { m_url = url; string path = PathUtils.MakeFilePath(assetBundleName, PathUtils.PathType.MobileDiskWrite); FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite); HTTPRequest http = new BestHTTP.HTTPRequest(new Uri(url), HTTPMethods.Head, (req, resp) => { if (resp == null) { stream.Dispose(); return; } if (resp.StatusCode == 416) { stream.Dispose(); return; } if (resp.HasHeaderWithValue("accept-ranges", "none")) { stream.Dispose(); return; } long remoteLength = GetLength(resp); if (remoteLength <= 0) { stream.Dispose(); return; } long localLength = stream.Length; if (localLength == remoteLength) { Loom.RunAsync(() => { m_data = new byte[localLength]; stream.Read(m_data, 0, (int)localLength); stream.Dispose(); Loom.QueueOnMainThread(() => { if (m_data != null && m_data.Length > 0) { m_abcr = AssetBundle.LoadFromMemoryAsync(m_data); } m_isDownloaded = true; }); }); return; } var downloadRequest = new HTTPRequest(req.Uri, HTTPMethods.Get, true, (downloadReq, downloadResp) => { Loom.RunAsync(() => { stream.Write(downloadResp.Data, 0, downloadResp.Data.Length); stream.Flush(); long length = stream.Length; m_data = new byte[length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(m_data, 0, m_data.Length); stream.Dispose(); Loom.QueueOnMainThread(() => { if (m_data != null && m_data.Length > 0) { m_abcr = AssetBundle.LoadFromMemoryAsync(m_data); } m_isDownloaded = true; }); }); }); //Debug.Log(req.Uri + "\n" + "length: " + localLength); downloadRequest.SetRangeHeader((int)localLength); downloadRequest.DisableCache = true; downloadRequest.Send(); //m_data = resp.Data; //m_isDownloaded = true; //if (m_data != null && m_data.Length > 0) //{ // m_abcr = AssetBundle.LoadFromMemoryAsync(m_data); //} }); http.DisableCache = true; http.Send(); }
public void requestImage() { HTTPRequest request = new HTTPRequest(new Uri(url), HTTPMethods.Get, imageCallback); request.Send(); }
internal Signal<BookImage> Load() { _request = new HTTPRequest(new Uri(_url), OnComplete); _request.OnProgress = OnDownloadProgress; _request.Send(); return _complete; }
/// <summary> /// Polling transport speficic function. Sends a GET request to the /poll path to receive messages. /// </summary> private void Poll() { pollRequest = new HTTPRequest(Connection.BuildUri(RequestTypes.Poll, this), HTTPMethods.Get, true, true, OnPollRequestFinished); Connection.PrepareRequest(pollRequest, RequestTypes.Poll); pollRequest.Timeout = this.PollTimeout; pollRequest.Send(); }
void DownloadImages() { // Set these metadatas to its initial values #if !BESTHTTP_DISABLE_CACHING allDownloadedFromLocalCache = true; #endif finishedCount = 0; for (int i = 0; i < Images.Length; ++i) { // Set a blank placeholder texture, overriding previously downloaded texture Textures[i] = new Texture2D(100, 150); // Construct the request var request = new HTTPRequest(new Uri(BaseURL + Images[i]), ImageDownloaded); #if !BESTHTTP_DISABLE_ALTERNATE_SSL request.UseAlternateSSL = true; #endif // Set the Tag property, we can use it as a general storage bound to the request request.Tag = Textures[i]; // Send out the request request.Send(); } }
// Calling this function again when the "DownloadProgress" key in the PlayerPrefs present will // continue the download void StreamLargeFileTest() { request = new HTTPRequest(new Uri(URL), (req, resp) => { switch (req.State) { // The request is currently processed. With UseStreaming == true, we can get the streamed fragments here case HTTPRequestStates.Processing: // Set the DownloadLength, so we can display the progress if (!PlayerPrefs.HasKey("DownloadLength")) { string value = resp.GetFirstHeaderValue("content-length"); if (!string.IsNullOrEmpty(value)) PlayerPrefs.SetInt("DownloadLength", int.Parse(value)); } // Get the fragments, and save them ProcessFragments(resp.GetStreamedFragments()); status = "Processing"; break; // The request finished without any problem. case HTTPRequestStates.Finished: if (resp.IsSuccess) { // Save any remaining fragments ProcessFragments(resp.GetStreamedFragments()); // Completly finished if (resp.IsStreamingFinished) { status = "Streaming finished!"; // We are done, delete the progress key PlayerPrefs.DeleteKey("DownloadProgress"); PlayerPrefs.Save(); request = null; } else status = "Processing"; } else { status = string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}", resp.StatusCode, resp.Message, resp.DataAsText); Debug.LogWarning(status); request = null; } break; // The request finished with an unexpected error. The request's Exception property may contain more info about the error. case HTTPRequestStates.Error: status = "Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"); Debug.LogError(status); request = null; break; // The request aborted, initiated by the user. case HTTPRequestStates.Aborted: status = "Request Aborted!"; Debug.LogWarning(status); request = null; break; // Ceonnecting to the server is timed out. case HTTPRequestStates.ConnectionTimedOut: status = "Connection Timed Out!"; Debug.LogError(status); request = null; break; // The request didn't finished in the given time. case HTTPRequestStates.TimedOut: status = "Processing the request Timed Out!"; Debug.LogError(status); request = null; break; } }); // Are there any progress, that we can continue? if (PlayerPrefs.HasKey("DownloadProgress")) // Set the range header request.SetRangeHeader(PlayerPrefs.GetInt("DownloadProgress")); else // This is a new request PlayerPrefs.SetInt("DownloadProgress", 0); #if !BESTHTTP_DISABLE_CACHING // If we are writing our own file set it true(disable), so don't duplicate it on the filesystem request.DisableCache = true; #endif // We want to access the downloaded bytes while we are still downloading request.UseStreaming = true; // Set a reasonable high fragment size. Here it is 5 megabytes. request.StreamFragmentSize = fragmentSize; // Start Processing the request request.Send(); }
//异步下载,参数 complete_param 是完成回调的执行参数 public static void DownLoad(string SrcFilePath, string SaveFilePath, object complete_param, LuaFunction progressHander, LuaFunction completeHander) { var request = new HTTPRequest(new Uri(SrcFilePath), (req, resp) => { List<byte[]> fragments = resp.GetStreamedFragments(); // Write out the downloaded data to a file: using (FileStream fs = new FileStream(SaveFilePath, FileMode.Append)) foreach (byte[] data in fragments) fs.Write(data, 0, data.Length); if (resp.IsStreamingFinished) { if (completeHander != null) { if (complete_param != null) { completeHander.call(req, resp,complete_param); } else { completeHander.call(req, resp); } Debug.Log("Download finished!"); } } }); request.OnProgress = (req, downloaded, length) => { if (progressHander != null) { double pg =Math.Round( (float)downloaded / (float)length,2); progressHander.call(pg); } }; request.UseStreaming = true; request.StreamFragmentSize = 1 * 1024 * 1024; // 1 megabyte request.DisableCache = true; // already saving to a file, so turn off caching request.Send(); }
/// <summary> /// Start to get the negotiation data. /// </summary> public void Start() { NegotiationRequest = new HTTPRequest(Connection.BuildUri(RequestTypes.Negotiate), HTTPMethods.Get, true, true, OnNegotiationRequestFinished); Connection.PrepareRequest(NegotiationRequest, RequestTypes.Negotiate); NegotiationRequest.Send(); HTTPManager.Logger.Information("NegotiationData", "Negotiation request sent"); }
// https://library.vuforia.com/articles/Solution/How-To-Use-the-Vuforia-Web-Services-API.htm#How-To-Update-a-Target IEnumerator PutUpdateTarget(bool updateImage = false) { Debug.Log("CustomMessage: PutUpdateTarget()"); // Setting up query. string requestPath = "/targets/" + currentImageData.UniqueTargetId; string serviceURI = url + requestPath; string httpAction = "PUT"; string contentType = "application/json"; string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime()); string metadataStr = jsonData; byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr); // Create new model to prepare for sending. PostNewTrackableRequest model = new PostNewTrackableRequest(); model.name = targetName; model.width = 64.0f; model.application_metadata = System.Convert.ToBase64String(metadata); if (updateImage) { // Create texture and encode pixels to base64. Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false); tex.SetPixels(texture.GetPixels()); tex.Apply(); byte[] image = tex.EncodeToPNG(); model.image = System.Convert.ToBase64String(image); } // Convert model to json. string requestBody = JsonUtility.ToJson(model); // Create ContentMD5. MD5 md5 = MD5.Create(); var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody)); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < contentMD5bytes.Length; i++) { sb.Append(contentMD5bytes[i].ToString("x2")); } string contentMD5 = sb.ToString(); string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath); // Build signature. HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key)); byte[] sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign); MemoryStream stream = new MemoryStream(sha1Bytes); byte[] sha1Hash = sha1.ComputeHash(stream); string signature = System.Convert.ToBase64String(sha1Hash); Debug.Log("<color=green>Signature: " + signature + "</color>"); // Build Http Request. BestHTTP.HTTPRequest request = new BestHTTP.HTTPRequest(new Uri(serviceURI)); request.MethodType = BestHTTP.HTTPMethods.Put; request.RawData = Encoding.UTF8.GetBytes(requestBody); request.AddHeader("Authorization", string.Format("VWS {0}:{1}", access_key, signature)); request.AddHeader("Content-Type", contentType); request.AddHeader("Date", date); request.Send(); yield return(StartCoroutine(request)); switch (request.State) { case BestHTTP.HTTPRequestStates.Error: Debug.Log("request error: " + request.Exception.Message); string errorText = request.Exception.Message; PrintStatusText("Exception: " + errorText); break; case BestHTTP.HTTPRequestStates.Finished: // There is an error if (request.Response.StatusCode != 200) { Debug.Log("request error: " + request.Response.Message); string result_code = JsonUtility.FromJson <VWSResponse>(request.Response.DataAsText).result_code; // The target is still being processed in Vuforia API. if (result_code == "TargetStatusNotSuccess") { PrintStatusText("Error: Profile is still being processed in Vuforia!"); } else { PrintStatusText("Error: " + result_code); } } else { Debug.Log("request success"); PrintStatusText("Saved!"); if (rescanCloudAfterEdit) { // We disable cloud tracking for x seconds. The reason why we do this is because it takes time for // Vuforia to actually delete the record. If we continue cloud tracking, it would retrack the record. DisableCloudTracking(2f); // To get all the tracked targets. For testing. // IEnumerable<Vuforia.ObjectTarget> obj = Vuforia.TrackerManager.Instance.GetTracker<Vuforia.ObjectTracker>().GetTargetFinder<Vuforia.ImageTargetFinder>().GetObjectTargets(); // IEnumerator myEnum = obj.GetEnumerator(); // while(myEnum.MoveNext()){ // print(myEnum.Current); // } // Clear local copy. Vuforia.TrackerManager.Instance.GetTracker <Vuforia.ObjectTracker>().GetTargetFinder <Vuforia.ImageTargetFinder>().ClearTrackables(false); } else { // Since the image is saved to the cloud, we can change the local copy. currentImageData.MetaData = metadataStr; currentImageData.TargetName = targetName; // Force update of target info. cloudContentManager.HandleTargetFinderResult(currentImageData); // The only issue with this method is we do not know the new tracking rating of the copy. // However, since our version of profiler does not show tracking rating, it should work fine. // Also, if the new image fails the processor on Vuforia's side, it wouldn't make sense to // change the local copy's data. However, it would be more convenient for the user to see // the new updated version. Therefore, when changing the local copy, we are assuming the // new image to be processed successfully. } // Close edit menu. ToggleEditMenu(); } break; } // Enable buttons. deleteDeleteButton.interactable = true; putEditButton.interactable = true; editButton.interactable = true; }
private void Start() { HTTPRequest request = new HTTPRequest(new Uri(APIUrl.UrlItems + PlayerPrefs.GetString("token")), HTTPMethods.Get, OnRequestFinished); Debug.Log(APIUrl.UrlItems + PlayerPrefs.GetString("token")); request.Send(); }
private IEnumerator GetImages(System.Action<string> errorCallback) { HTTPRequest req = new HTTPRequest(new System.Uri("http://one.digitnode.com/images/")); req.Send(); yield return StartCoroutine(req); if(req.Response==null || !req.Response.IsSuccess) { errorCallback("Get DigitNode Error"); yield break; } string data = req.Response.DataAsText; imageList = JsonConvert.DeserializeObject<ImageList>(data); yield return null; }