public void GetVideoThumbnail(string videoUrl, RequestComplete resultHandler) { // get the video's ID string videoId = videoUrl.Substring(videoUrl.LastIndexOf("/") + 1); videoId = videoId.Substring(0, videoId.IndexOf(".")); // get the metadata for this video, which will contain the thumbnail url RestRequest request = new RestRequest(Method.GET); request.RequestFormat = DataFormat.Xml; string requestUrl = string.Format("https://vimeo.com/api/v2/video/{0}.xml", videoId); HttpRequest.ExecuteAsync <VimeoVideo>(requestUrl, request, delegate(System.Net.HttpStatusCode statusCode, string statusDescription, VimeoVideo model) { if (Rock.Mobile.Network.Util.StatusInSuccessRange(statusCode) == true) { RequestThumbnail(model.ThumbnailLarge, resultHandler); } else { resultHandler(statusCode, statusDescription, null); } }); }
public static IEnumerator RequestByWWW(string url, RequestComplete loadComplete) { if (string.IsNullOrEmpty(url)) { Debug.LogError("RequestAssetByWWW url is null or empty. "); yield break; } using (WWW www = new WWW(url)) { yield return(www); try { if (www.isDone && string.IsNullOrEmpty(www.error)) { loadComplete(www); } else { Debug.LogErrorFormat("LoadAssetByWWW load '{0}'.error '{1}'. ", url, www.error); loadComplete(null, www.error); } } catch (Exception e) { Debug.LogErrorFormat("LoadAssetByWWW '{0}' error '{1}', {2}. ", url, e.Message, e.StackTrace); } finally { www.Dispose(); } } }
/// <summary> /// 人脸识别 /// </summary> /// <param name="img"></param> /// <param name="complete"></param> /// <returns></returns> public IEnumerator PostDetect(byte[] img, RequestComplete complete) { WWWForm wwwForm = new WWWForm(); wwwForm.AddField("api_key", Utility.Http.EscapeString("api-key")); wwwForm.AddField("api_secret", Utility.Http.EscapeString("api-secret")); wwwForm.AddField("return_attributes", "emotion"); // int string 类型 详情参数查看 https://console.faceplusplus.com.cn/documents/4888373 wwwForm.AddBinaryData("image_file", img); // 二进制 类型 yield return(UtilityMisc.RequestByWWW(FaceppV3Detect, wwwForm, complete)); }
/// <summary> /// Called to read the response asyncroneusly /// </summary> /// <param name="ar"></param> private void ReadResponse(IAsyncResult ar) { Stream stream = null; int bytesRead = 0; HttpClientResult result = HttpClientResult.Error; try { lock (_lock) { stream = (Stream)ar.AsyncState; bytesRead = stream.EndRead(ar); if (bytesRead > 0) { //add to the exiting data _dataBuilder.AddChunkReference(_buffer, bytesRead); //make a new chunk _buffer = new byte[MAX_BUFFER_SIZE]; //continue reading stream.BeginRead(_buffer, 0, MAX_BUFFER_SIZE, new AsyncCallback(ReadResponse), stream); } else { //construct the full response _response = _dataBuilder.ToArray(); result = HttpClientResult.Success; } } } catch { //we don't care that much for the errors that occur here } finally { if (bytesRead == 0) { //if the caller was waiting on the request complete event allow continuation _requestCompleteEvent.Set(); //we're done reading close the connection and trigger the event with the collected response //the result will be success if (RequestComplete != null) { RequestComplete.Invoke (new HttpClientRequestCompleteEventArgs(new HttpResponseInfo(_response))); } _connection.Close(); } } }
void RequestThumbnail(string thumbnailUrl, RequestComplete resultHandler) { // grab the actual image RestRequest request = new RestRequest(Method.GET); // get the raw response HttpRequest.ExecuteAsync(thumbnailUrl, request, delegate(System.Net.HttpStatusCode statusCode, string statusDescription, byte[] model) { if (Rock.Mobile.Network.Util.StatusInSuccessRange(statusCode) == true) { MemoryStream memoryStream = new MemoryStream(model); resultHandler(statusCode, statusDescription, memoryStream); memoryStream.Dispose( ); } else { resultHandler(statusCode, statusDescription, null); } }); }
// This gets called after failure or success protected void OnRequestComplete() { RequestComplete?.Invoke(this, null); }
public void SetServiceCallbacks(ServiceRequestComplete serviceRequestComplete, RequestComplete requestComplete) { OnServiceDetailRequestComplete = null; OnServiceRequestComplete = null; OnServiceRequestComplete = serviceRequestComplete; OnRequestError = requestComplete; }
public void SetMapEvents(RequestComplete requestComplete, RequestComplete requestError, RequestComplete requestIdentifyComplete) { OnMapRequestComplete = OnRequestError = OnIdentifyRequestComplete = null; OnMapRequestComplete += requestComplete; OnRequestError += requestError; OnIdentifyRequestComplete += requestIdentifyComplete; }
public void SetSearchCallback(RequestComplete onRequestComplete, RequestComplete onRequestError) { OnSearchRequestComplete = null; OnSearchRequestComplete += onRequestComplete; OnRequestError += onRequestError; }
/// <summary> /// Sends the specified request to the server /// (Proxy not supported) /// </summary> /// <param name="parsedRequest"></param> /// <param name="host"></param> /// <param name="port"></param> /// <param name="https"></param> public void SendRequest(HttpRequestInfo parsedRequest, string host, int port, bool https) { _requestCompleteEvent.Reset(); _dataBuilder = new ByteArrayBuilder(); if (_connection == null) { _connection = new HttpClientConnection(host, port, https); } try { //connect if (_connection.Connect()) { bool isProxy = _connection.Host != host; //add connection closed header only this is supported at the moment parsedRequest.Headers["Connection"] = "close"; if (isProxy) { parsedRequest.Headers["Proxy-Connection"] = "close"; } // Turn off accepting of gzip/deflate //parsedRequest.Headers.Remove("Accept-Encoding"); //calculate the content length if (parsedRequest.ContentData != null) { parsedRequest.Headers["Content-Length"] = parsedRequest.ContentData.Length.ToString(); } parsedRequest.Host = host; parsedRequest.Port = port; parsedRequest.IsSecure = https; if (isProxy && https) { //send a connect message to the proxy SendConnect(host, port); } byte[] reqBytes = Constants.DefaultEncoding.GetBytes(parsedRequest.ToString(isProxy && !https)); //write to the stream _connection.Stream.Write(reqBytes, 0, reqBytes.Length); //start reading _buffer = new byte[MAX_BUFFER_SIZE]; _connection.Stream.BeginRead(_buffer, 0, MAX_BUFFER_SIZE, new AsyncCallback(ReadResponse), _connection.Stream); } else { throw new Exception("Cannot connect to server"); } } catch (Exception ex) { SdkSettings.Instance.Logger.Log(TraceLevel.Error, "HttpClient error sending request {0}", ex.Message); //notify the caller that the request was completed with an error if (RequestComplete != null) { RequestComplete.Invoke( new HttpClientRequestCompleteEventArgs()); RequestCompleteEvent.Set(); } _connection.Close(); } }
public static void MakeRequest(string verb, string requestUrl, string obj, RequestComplete handle) { WebRequest request = WebRequest.Create(requestUrl); request.Method = verb; string respstring = String.Empty; using (MemoryStream buffer = new MemoryStream()) { if ((verb == "POST") || (verb == "PUT")) { request.ContentType = "text/www-form-urlencoded"; int length = 0; using (StreamWriter writer = new StreamWriter(buffer)) { writer.Write(obj); writer.Flush(); } length = obj.Length; request.ContentLength = length; try { request.BeginGetRequestStream(delegate(IAsyncResult res) { Stream requestStream = request.EndGetRequestStream(res); requestStream.Write(buffer.ToArray(), 0, length); requestStream.Close(); }, null); } catch (Exception e) { MainConsole.Instance.DebugFormat("[FORMS]: exception occured on sending request to {0}: " + e, requestUrl); return; } finally { } WebResponse response = null; request.BeginGetResponse(delegate(IAsyncResult res2) { try { // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't // documented in MSDN response = request.EndGetResponse(res2); Stream respStream = null; try { respStream = response.GetResponseStream(); if (respStream != null) { using (StreamReader reader = new StreamReader(respStream)) { respstring = reader.ReadToEnd(); } } } catch (InvalidOperationException) { } finally { if (respStream != null) { respStream.Close(); } response.Close(); } handle(respstring); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { if (e.Response is HttpWebResponse) { HttpWebResponse httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode != HttpStatusCode.NotFound) { // We don't appear to be handling any other status codes, so log these feailures to that // people don't spend unnecessary hours hunting phantom bugs. MainConsole.Instance.DebugFormat( "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}", verb, requestUrl, httpResponse.StatusCode); } } } else { MainConsole.Instance.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e); } } catch (Exception e) { MainConsole.Instance.ErrorFormat( "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e); } }, null); } } }
public void SetRequestCompleteCallBack(RequestComplete callback) { requestComplete = callback; }
/// <summary> /// Request complete invoker /// </summary> protected void OnRequestComplete(Guid id, LogInfo requestLog, LogInfo responseLog) { RequestComplete?.Invoke(this, new RequestEventArgs(id, requestLog, responseLog)); }
public void GetVideoThumbnail( string videoUrl, RequestComplete resultHandler ) { // get the video's ID string videoId = videoUrl.Substring( videoUrl.LastIndexOf( "/" ) + 1 ); videoId = videoId.Substring( 0, videoId.IndexOf( "." ) ); // get the metadata for this video, which will contain the thumbnail url RestRequest request = new RestRequest( Method.GET ); request.RequestFormat = DataFormat.Xml; string requestUrl = string.Format( "http://vimeo.com/api/v2/video/{0}.xml", videoId ); HttpRequest.ExecuteAsync<VimeoVideo>( requestUrl, request, delegate(System.Net.HttpStatusCode statusCode, string statusDescription, VimeoVideo model) { if( Rock.Mobile.Network.Util.StatusInSuccessRange( statusCode ) == true ) { RequestThumbnail( model.ThumbnailLarge, resultHandler ); } else { resultHandler( statusCode, statusDescription, null ); } } ); }
void RequestThumbnail( string thumbnailUrl, RequestComplete resultHandler ) { // grab the actual image RestRequest request = new RestRequest( Method.GET ); // get the raw response HttpRequest.ExecuteAsync( thumbnailUrl, request, delegate(System.Net.HttpStatusCode statusCode, string statusDescription, byte[] model ) { if ( Rock.Mobile.Network.Util.StatusInSuccessRange( statusCode ) == true ) { MemoryStream memoryStream = new MemoryStream( model ); resultHandler( statusCode, statusDescription, memoryStream ); memoryStream.Dispose( ); } else { resultHandler( statusCode, statusDescription, null ); } } ); }