public async void ScheduleTweet(string text, DateTime dueTime, RequestCallback callback) { TimeSpan diff = dueTime - DateTime.Now; long delay = (long)diff.TotalMilliseconds; string url = String.Format(SensitiveData.ScheduleUriformat, Uri.EscapeDataString(accessToken), Uri.EscapeDataString(text), delay); var request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response; try { response = (HttpWebResponse)await request.GetResponseAsync(); } catch (WebException e) { response = (HttpWebResponse)e.Response; } if (callback != null) { callback(this, response); } }
public void destroy_geo_cache(int geo_cache_id, RequestCallback callback) { HTTP http = HTTP.post(url_to("api/geo_caches/" + geo_cache_id)); http.request.method = "DELETE"; http.send(this, callback); }
/// <summary> /// 添加书的构造 /// </summary> /// <param name="pRequestStr"></param> /// <param name="pCallBack"></param> public RequestParam(string pRequestStr, RequestCallback pCallBack, Promotion pbook, BookProfebSc psc) { callBack = pCallBack; Request = Encoding.UTF8.GetBytes(pRequestStr);; book = pbook; Param = psc; }
public static void SetFsPluginCallbacks(ProgressCallback progress, ProgressCallbackW progressW, LogCallback log, LogCallbackW logW, RequestCallback request, RequestCallbackW requestW, FsCryptCallback crypt, FsCryptCallbackW cryptW) { if (progressCallback == null) { progressCallback = progress; } if (progressCallbackW == null) { progressCallbackW = progressW; } if (logCallback == null) { logCallback = log; } if (logCallbackW == null) { logCallbackW = logW; } if (requestCallback == null) { requestCallback = request; } if (requestCallbackW == null) { requestCallbackW = requestW; } if (fsCryptCallback == null) { fsCryptCallback = crypt; } if (fsCryptCallbackW == null) { fsCryptCallbackW = cryptW; } }
public static void checkForTheNewVersion(RequestCallback callback) { Dictionary <string, object> requestMap = new Dictionary <string, object>(); requestMap.Add(PARAM_ACTION, ACTION_CHECK_NEW_VERSION); performCommand(requestMap, callback); }
/// <summary> /// PublishJSON /// /// Send a message to a channel. /// </summary> /// <param name="json"> /// A <see cref="System.Object"/> /// </param> /// <param name="callback"> /// A <see cref="RequestCallback"/> /// </param> IEnumerator PublishJSON(string json, RequestCallback callback) { // Generate String to Sign string signature = "0"; if (!string.IsNullOrEmpty(secretKey)) { string string_to_sign = string.Format("{0}/{1}/{2}/{3}/{4}", pubKey, subKey, secretKey, channel, json); // Sign Message signature = PubNub.Tools.MD5(string_to_sign); } // Build URL string[] url = { "publish", pubKey, subKey, signature, channel, "0", json }; return(Request(url, response => { if (callback != null) { callback(response); } })); }
public Task InitiateRequestAsync(RequestCallback callback) { var httpClient = _httpClientFactory.CreateClient(Constants.ThirdPartyClientName); var jsonBody = new StringContent(JsonSerializer.Serialize(callback), Encoding.UTF8, "application/json"); // Would use Polly to implement a retry patttern like below. // Commented it out because the endpoint specified returns a 405 so we would keep getting an exception //var maxRetryAttempts = 3; //var pauseBetweenFailures = TimeSpan.FromSeconds(2); //var retryPolicy = Policy // .Handle<HttpRequestException>() // .WaitAndRetryAsync(maxRetryAttempts, i => pauseBetweenFailures); //await retryPolicy.ExecuteAsync(async () => //{ // var response = await httpClient.PostAsync(Constants.ThirdPartyUrl, jsonBody); // // Throws an exception if theIsSuccessStatusCode is false // response.EnsureSuccessStatusCode(); //}); // Just returning successful task for this exercise return(Task.FromResult <object>(null)); }
//attempt to login to KerbalX with the user's auth token. If the token doesn't exist, or is no longer valid the response will be a 401 internal void login(RequestCallback callback) { try{ if (File.Exists(KerbalXAPI.token_path)) { KXAPI.log("Logging into KerbalX.com with Token..."); string current_token = File.ReadAllText(KerbalXAPI.token_path); authenticate_token(current_token, (resp, code) => { if (code == 200) { KXAPI.log("Logged in"); var resp_data = JSON.Parse(resp); KerbalXAPI.kx_username = resp_data["username"]; KerbalXAPI.token = current_token; } else { KXAPI.log("Login token is invalid"); } callback(resp, code); }); } else { callback("", 401); } } catch { callback("", 401); } }
/// <summary> /// Get all the bytes by PATH. /// </summary> public byte[] ReadAllBytes(string path, RequestCallback callback = null) { byte[] data = TryCacheData(path); if (data == null) { data = TryStreamingAssets(path); } if (data == null) { if (callback != null) { if (requestCallback == null) { requestCallback = callback; } else { JCS_Debug.LogWarning("Override request callback is denied"); } } AddDownloadTarget(path); data = REQ_KEY; // Set to `wait` key! } return(data); }
private IEnumerator GetData() { UnityWebRequest www = UnityWebRequest.Get(requestURL); yield return(www.SendWebRequest()); bool success = false; if (www.isNetworkError || www.isHttpError) { if (JCS_GameSettings.instance.DEBUG_MODE) { JCS_Debug.LogWarning(www.error); } } else { mResultData = www.downloadHandler.data; WriteFileAsCache(requestPath, mResultData); success = true; } if (requestCallback != null) { requestCallback.Invoke(requestPath, success); } requestCallback = null; downloadList.Remove(requestPath); requesting = false; }
addCallback(Reference @ref, Reference wellKnownRef, int ttl, GetEndpointsCallback cb) { _m.Lock(); try { RequestCallback callback = new RequestCallback(@ref, ttl, cb); if (_response) { callback.response(_locatorInfo, _proxy); } else if (_exception != null) { callback.exception(_locatorInfo, _exception); } else { _callbacks.Add(callback); if (wellKnownRef != null) { // This request is to resolve the endpoints of a cached well-known object ref _wellKnownRefs.Add(wellKnownRef); } if (!_sent) { _sent = true; send(true); } } } finally { _m.Unlock(); } }
addCallback(Reference @ref, Reference wellKnownRef, int ttl, GetEndpointsCallback cb) { RequestCallback callback = new RequestCallback(@ref, ttl, cb); lock (this) { if (!_response && _exception == null) { _callbacks.Add(callback); if (wellKnownRef != null) { // This request is to resolve the endpoints of a cached well-known object ref _wellKnownRefs.Add(wellKnownRef); } if (!_sent) { _sent = true; send(); } return; } } if (_response) { callback.response(_locatorInfo, _proxy); } else { Debug.Assert(_exception != null); callback.exception(_locatorInfo, _exception); } }
internal void send(KerbalXAPI api, RequestCallback callback, bool authenticate = true) { if (String.IsNullOrEmpty(api.client_version) || String.IsNullOrEmpty(api.client)) { KXAPI.log("client info has not been set"); return; } if (authenticate) { if (api.logged_in) { set_header("token", KerbalXAPI.token); } else { KerbalXLoginUI.add_login_callback(api, (login_succsessful) => { if (login_succsessful) { this.send(api, callback, authenticate); } }); KerbalXLoginUI.open(); return; } } set_header("MODCLIENT", api.client); set_header("MODCLIENTVERSION", api.client_version); set_header("MODCLIENTSIGNITURE", api.client_signiture); set_header("KSPVERSION", Versioning.GetVersionString()); if (RequestHandler.instance == null) { KerbalXAPIHelper.instance.start_request_handler(); } RequestHandler.instance.send_request(api, request, callback); }
public void search_geo_caches(WWWForm search_params, RequestCallback callback) { HTTP http = HTTP.post(url_to("api/geo_caches/search"), search_params); http.set_header("Content-Type", "multipart/form-data"); http.send(this, callback); }
//Craft POST and PUT requests //Send new craft to Mun....or KerbalX.com as a POST request public void upload_craft(WWWForm craft_data, RequestCallback callback) { HTTP http = HTTP.post(url_to("api/craft"), craft_data); http.set_header("Content-Type", "multipart/form-data"); http.send(this, callback); }
public void lookup_parts(WWWForm part_info, RequestCallback callback) { HTTP http = HTTP.post(url_to("api/lookup_parts"), part_info); http.set_header("Content-Type", "multipart/form-data"); http.send(this, callback); }
internal void AddCallback(Reference reference, Reference?wellKnownRef, int ttl, IGetEndpointsCallback?cb) { var callback = new RequestCallback(reference, ttl, cb); lock (this) { if (!_response && _exception == null) { _callbacks.Add(callback); if (wellKnownRef != null) { // This request is to resolve the endpoints of a cached well-known object ref _wellKnownRefs.Add(wellKnownRef); } if (!_sent) { _sent = true; Send(); } return; } } if (_response) { callback.Response(LocatorInfo, _proxy); } else { Debug.Assert(_exception != null); callback.Exception(LocatorInfo, _exception); } }
public RestClientHandler(RequestCallback callback) { this.callback = callback; SslProtocols = SslProtocols.Tls12; ClientCertificateOptions = ClientCertificateOption.Automatic; }
/// <summary> /// Runs the client sending request/response messages example. /// </summary> /// <param name="cancellationToken">A token used to end the client example.</param> /// <param name="args">A single string should be used for the server url.</param> public async Task Run(CancellationToken cancellationToken, string[] args) { var serverUrl = args[0]; var session = Diffusion.Sessions.Principal("control").Password("password").Open(serverUrl); var messagingControl = session.MessagingControl; var requestCallback = new RequestCallback(); while (!cancellationToken.IsCancellationRequested) { // To obtain session IDs we will use in this example request to filter messaging int requestsSent = await messagingControl.SendRequestToFilterAsync( "$Principal EQ 'client'", messagingPath, "Hello?", requestCallback, cancellationToken); if (requestsSent > 0) { requestCallback.ResponseEvent.WaitOne(); // Send message to a session using obtained session ID var response = await messagingControl.SendRequestAsync <string, string>( requestCallback.SessionId, messagingPath, "Time", cancellationToken); WriteLine($"Received response: '{response}'."); } await Task.Delay(TimeSpan.FromMilliseconds(1000)); } // Close the session session.Close(); }
public TileRequest CreateTileRequest(long id, RequestCallback callback) { tId.Set(id); string url = urlPrefix + tId.ToURL() + tokenSufix; string file = cachePath + tId.Z + Path.DirectorySeparatorChar + tId.X + "_" + tId.Y + ".tile"; return(new TileRequest(id, file, url, callback)); }
public void GameInit(string uid, RequestCallback callback) { List<NameValuePair> paramsList = new List<NameValuePair>(); paramsList = InitCommParm(); paramsList.Add(new NameValuePair("uid",uid)); StartCoroutine(Request("GameInit", paramsList, funGameInit, HTTPMETHOD.GET, callback)); }
//Update existing craft on KerbalX as a PUT request with the KerbalX database ID of the craft to be updated public void update_craft(int id, WWWForm craft_data, RequestCallback callback) { HTTP http = HTTP.post(url_to("api/craft/" + id), craft_data); http.request.method = "PUT"; //because unity's PUT method doesn't take a form, so we create a POST with the form and then change the verb. http.set_header("Content-Type", "multipart/form-data"); http.send(this, callback); }
//nukes the authentication token file and user variables and sets the login gui to enable login again. internal void logout(RequestCallback callback) { token = null; kx_username = null; File.Delete(KerbalXAPI.token_path); callback("", 200); KXAPI.log("Logged out of KerbalX"); }
public ParallelHttpRequest(HttpRequestMessage message, RequestCallback callback, object reference = default, CancellationToken cancellationToken = default) { Reference = reference ?? new object(); Message = message; Callback = callback; CancellationToken = cancellationToken; }
public IEnumerator Request(string url, WWWForm form, RequestCallback callback) { WWW www = new WWW(url, form); yield return(www); callback(www.error, www); }
public IEnumerator Request(string url, byte[] postData, RequestCallback callback) { WWW www = new WWW(url, postData); yield return(www); callback(www.error, www); }
public void update_geo_cache(int geo_cache_id, WWWForm geo_cache_data, RequestCallback callback) { HTTP http = HTTP.post(url_to("api/geo_caches/" + geo_cache_id), geo_cache_data); http.request.method = "PUT"; http.set_header("Content-Type", "multipart/form-data"); http.send(this, callback); }
public Request(int RequestId, byte[] data, bool SendResultBack, RequestCallback Callback = null) { this.RequestId = RequestId; this.syncObject = new SyncObject(); this.PacketData = data; this.Async = Callback != null; this.Callback = Callback; this.SendResultBack = SendResultBack; }
public void GameInit(string uid, RequestCallback callback) { List <NameValuePair> paramsList = new List <NameValuePair>(); paramsList = InitCommParm(); paramsList.Add(new NameValuePair("uid", uid)); StartCoroutine(Request("GameInit", paramsList, funGameInit, HTTPMETHOD.GET, callback)); }
public async Task Request(UtilityCard utilityCard, RequestCallback requestCallback) { string actionName = await FindActionByScore(utilityCard); if (requestCallback != null) { requestCallback(actionName); } }
public void AsyncRequest(string message, RequestCallback callback) { // callback can be null UInt32 seqNum = NextSequenceNumber++; lock (this) { OutstandingRequests[seqNum] = callback; } PrimitiveSend(MESSAGE_TYPE_REQUEST, seqNum, message); }
private static void performCommand(Dictionary <string, object> requestMap, RequestCallback callback) { string time = utils.Utils.getCurrentTimestamp().ToString(); string h = string.Format("{0}_{1}", time, System.Text.Encoding.UTF8.GetString(SALT)); requestMap[PARAM_TIME] = time; requestMap[PARAM_HASH] = utils.Utils.createMD5ForString(h); RequestManager.getInstance().performGetRequest(SERVER_URL, requestMap, callback); }
internal static void SetNotificationCallback(Message.MessageType type, Message.Callback callback) { if (callback == null) { throw new Exception("Cannot provide a null notification callback."); } notificationCallbacks[type] = new RequestCallback(callback); }
public RequestProcessingManager(RequestCallback callback) { this.m_callback = callback; m_requestQueue = new ThreadSafeQueue<IRequestObject>(); m_pool = new Semaphore(0, m_capacity); m_continueWork = new ManualResetEvent(false); StartDequeueThread(); }
public EventHttpListener(RequestCallback cb) { LibLocator.TryToLoadDefaultIfNotInitialized(); _cb = cb; _eventBase = Event.EventBaseNew(); if (_eventBase.IsInvalid) throw new IOException("Unable to create event_base"); _evHttp = Event.EvHttpNew(_eventBase); if (_evHttp.IsInvalid) { Dispose(); throw new IOException("Unable to create evhttp"); } }
public IEnumerator Request(string requestName,List<NameValuePair> paramsList, string urlPrefix, HTTPMETHOD methodType, RequestCallback callback) { WWW www = null; string url = string.Empty; url = mServerAddress + urlPrefix; if(methodType == HTTPMETHOD.GET) { for(int i = paramsList.Count-1; i >=0; i --) { url = url + paramsList[i].mKey + "=" + paramsList[i].mValue + "&"; } url = url.Remove(url.Length - 1); www = new WWW(url); } else { url = url.Remove(url.Length - 1); WWWForm wwwForm = new WWWForm(); for(int i = paramsList.Count-1; i >=0; i --) { wwwForm.AddField(paramsList[i].mKey,paramsList[i].mValue); } www= new WWW(url, wwwForm); } Debug.Log(requestName+" ::::::::: "+url); yield return www; if (www.error == null) { callback.OnRequestSuccess(requestName,www.text); } else { //网络异常,for example :no net callback.OnRequestFailed(requestName); } }
public async void ScheduleTweet(string text, DateTime dueTime, RequestCallback callback) { TimeSpan diff = dueTime - DateTime.Now; long delay = (long)diff.TotalMilliseconds; string url = String.Format(SensitiveData.ScheduleUriformat, Uri.EscapeDataString(accessToken), Uri.EscapeDataString(text), delay); var request = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response; try { response = (HttpWebResponse)await request.GetResponseAsync(); } catch (WebException e) { response = (HttpWebResponse)e.Response; } if (callback != null) callback(this, response); }
/// <summary> /// Start /// </summary> /// <param name="Done"></param> public void Start(RequestCallback Done = null) { Callback = Done; Core.History("Request.Start()"); try { THREAD = Core.Threading.CreateThread(ProcessThread, "RequestThread"); Core.Threading.Execute(THREAD); }catch(Exception ex) { Core.ExceptionHandler(ex); } }
public Request(RequestCallback Callback, string URL, string Path) { this.Callback = Callback; this.URL = URL; this.Path = Path; }
public void CreateRequest(DownloadType Type, RequestCallback Callback, string URL, string Path = "") { switch (Type) { case DownloadType.API: APIRequests.Enqueue(new Request(Callback, URL, Path)); break; case DownloadType.Wallpaper: WallpaperRequests.Enqueue(new Request(Callback, URL, Path)); break; case DownloadType.Thumbnail: ThumbnailRequests.Enqueue(new Request(Callback, URL, Path)); break; } }
addCallback(Reference @ref, Reference wellKnownRef, int ttl, GetEndpointsCallback cb) { _m.Lock(); try { RequestCallback callback = new RequestCallback(@ref, ttl, cb); if(_response) { callback.response(_locatorInfo, _proxy); } else if(_exception != null) { callback.exception(_locatorInfo, _exception); } else { _callbacks.Add(callback); if(wellKnownRef != null) { // This request is to resolve the endpoints of a cached well-known object ref _wellKnownRefs.Add(wellKnownRef); } if(!_sent) { _sent = true; send(true); } } } finally { _m.Unlock(); } }
public void addCallback(Reference @ref, Reference wellKnownRef, int ttl, GetEndpointsCallback cb) { RequestCallback callback = new RequestCallback(@ref, ttl, cb); lock(this) { if(!_response && _exception == null) { _callbacks.Add(callback); if(wellKnownRef != null) { // This request is to resolve the endpoints of a cached well-known object ref _wellKnownRefs.Add(wellKnownRef); } if(!_sent) { _sent = true; send(); } return; } } if(_response) { callback.response(_locatorInfo, _proxy); } else { Debug.Assert(_exception != null); callback.exception(_locatorInfo, _exception); } }
/// <summary> /// Request URL /// </summary> /// <param name="url_components"> /// A <see cref="List<System.String>"/> /// </param> /// <param name="rqcallback"> /// A <see cref="RequestCallback"/> /// </param> IEnumerator Request(string[] url_components, RequestCallback rqcallback) { var url_builder = new StringBuilder(origin); // Generate URL with UTF-8 Encoding foreach (string url_bit in url_components) { url_builder.AppendFormat("/{0}", PubNub.Tools.EncodeURIcomponent(url_bit)); } // Fail if string too long if (url_builder.Length > limit) { DB.LogError("request url too long"); rqcallback(null); } using (WWW request = new WWW(url_builder.ToString())) { while (!request.isDone) { yield return null; } if (!string.IsNullOrEmpty(request.error)) { DB.LogError(string.Format("request error: {0}", request.error)); rqcallback(null); } else { rqcallback((List<object>) Json.Deserialize(request.text)); } } }
/// <summary> /// PublishJSON /// /// Send a message to a channel. /// </summary> /// <param name="json"> /// A <see cref="System.Object"/> /// </param> /// <param name="callback"> /// A <see cref="RequestCallback"/> /// </param> IEnumerator PublishJSON(string json, RequestCallback callback) { // Generate String to Sign string signature = "0"; if (!string.IsNullOrEmpty(secretKey)) { string string_to_sign = string.Format("{0}/{1}/{2}/{3}/{4}", pubKey, subKey, secretKey, channel, json); // Sign Message signature = PubNub.Tools.MD5(string_to_sign); } // Build URL string[] url = { "publish", pubKey, subKey, signature, channel, "0", json }; return Request(url, response => { if (callback != null) { callback(response); } }); }
/// <summary> /// Publish the specified message. /// </summary> /// <param name='message'> /// Message. /// </param> public IEnumerator Publish(object message, RequestCallback callback) { return PublishJSON(Json.Serialize(message), callback); }
public void postToStream(string message, RequestCallback cb) { rcb = cb; _graphRequest("feed", new string[] {"message", message}, "POST"); }
public EventHttpListener(RequestCallback cb) { LibLocator.TryToLoadDefaultIfNotInitialized(); _cb = cb; }
public EventHttpListener(RequestCallback cb) { _cb = cb; }
public void postToStream(string message, string picture, string link, string name, string caption, string description, RequestCallback cb) { rcb = cb; _graphRequest("feed", new string[] {"message", message, "picture", picture, "link", link, "name", name, "caption", caption, "description", description}, "POST"); }