private void PostJsonRequest(string url, WebhooksRequest forwardRequest, HttpRequestCallback callback, object userState = null, bool callAsync = false) { var stream = new MemoryStream(); var json = JsonConvert.SerializeObject(forwardRequest, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, TypeNameHandling = TypeNameHandling.None, }); var data = Encoding.UTF8.GetBytes(json); stream.Write(data, 0, data.Length); var request = new HttpRequest { Url = url, Method = "POST", Accept = "application/json", ContentType = "application/json", Callback = callback, UserState = userState, CustomHeaders = this.customHttpHeaders, DataStream = stream, Async = callAsync }; this.PluginHost.LogDebug(string.Format("PostJsonRequest: {0} - {1}", url, json)); this.PluginHost.HttpRequest(request); }
/// <summary> /// 同步POST /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <param name="callback"></param> private static IEnumerator PostSyn(string url, string postData, HttpRequestCallback callback) { string htmlStr = string.Empty; string _responseInfo = string.Empty; Encoding encoding = Encoding.GetEncoding("UTF-8"); //创建一个客户端的Http请求实例 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; byte[] _data = Encoding.UTF8.GetBytes(postData); request.ContentLength = _data.Length; request.ReadWriteTimeout = 60000; Stream requestStream = request.GetRequestStream(); requestStream.Write(_data, 0, _data.Length); requestStream.Close(); //获取当前Http请求的响应实例 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); if (responseStream != null) { var sr = new StreamReader(responseStream, encoding); //返回结果网页(html)代码 _responseInfo = sr.ReadToEnd(); } App.logManager.Info("--- post back info :" + _responseInfo); callback(_responseInfo); yield return(null); }
public static bool RequestData(String url, HttpRequestCallback callback) { WebRequest request = WebRequest.Create(url); request.Proxy = null; //special credentials we have for downloading newer versions request.Credentials = new NetworkCredential("zero.updates", "1CB858EE08E9"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { return(false); } Stream dataStream = response.GetResponseStream(); //let the user handle any custom logic with the data stream callback(dataStream); dataStream.Close(); response.Close(); return(true); }
/// <summary> /// HttpWebRequest:Post /// </summary> /// <param name="url"></param> /// <param name="data"></param> public static void SendRequest1(string postData, string url, HttpRequestCallback callback = null) { if (url == null || url.Equals("")) { App.logManager.Info("--- httpHelper url is null ---"); return; } if (postData == null) { postData = ""; } if (callback == null) { PostAsyn(url, postData); } else { CoroutineTask task = App.objectPoolManager.GetObject <CoroutineTask>(); task.routine = PostSyn(url, postData, callback); task.Start(); task.callback = (t) => { App.objectPoolManager.ReleaseObject(t); }; } }
/// <summary> /// Add a request handler /// </summary> /// <param name="method">HTTP verb to match, or null to skip verb matching</param> /// <param name="contentType">Content-Type header to match, or null to skip Content-Type matching</param> /// <param name="path">Request URI path regular expression to match, or null to skip URI path matching</param> /// <param name="callback">Callback to fire when an incoming request matches the given pattern</param> public void AddHandler(string method, string contentType, string path, HttpRequestCallback callback) { HttpRequestSignature signature = new HttpRequestSignature(); signature.Method = method; signature.ContentType = contentType; signature.Path = path; AddHandler(new HttpRequestHandler(signature, callback)); }
public UUID CreateCapability(HttpRequestCallback localHandler, bool clientCertRequired) { UUID id = UUID.Random(); CapsRedirector redirector = new CapsRedirector(localHandler, null, clientCertRequired); lock (syncRoot) fixedCaps.Add(id, redirector); return id; }
public void RemoveHandlers(HttpRequestCallback callback) { lock (m_handlersWriteLock) { List <HttpRequestHandler> newHandlers = new List <HttpRequestHandler>(m_requestHandlers.Length - 1); for (int i = 0; i < m_requestHandlers.Length; i++) { if (m_requestHandlers[i].Callback != callback) { newHandlers.Add(m_requestHandlers[i]); } } m_requestHandlers = newHandlers.ToArray(); } }
public void Set404Handler(HttpRequestCallback callback) { m_notFoundHandler = new HttpRequestHandler(null, callback, true); }
/// <summary> /// Set a callback to override the default 404 (Not Found) response /// </summary> /// <param name="callback">Callback that will be fired when an unhandled /// request is received, or null to reset to the default handler</param> public void Set404Handler(HttpRequestCallback callback) { notFoundHandler = callback; }
/// <summary> /// Try to get web content /// </summary> /// <param name="url">requested url</param> /// <param name="action">callback for request done</param> public void Request( string url, HttpMethod method, List<KeyValuePair<string, string>> httpPostData, HttpRequestCallback action ) { QueueItem item = new QueueItem() { Action = action, Url = url, Method = method, PostData = httpPostData }; AddQueueItem( item ); }
public StreamHandler(string httpMethod, string path, HttpRequestCallback callback) : base(httpMethod, path) { m_callback = callback; }
public CapsRedirector(HttpRequestCallback localCallback, Uri remoteHandler, bool clientCertRequired) { LocalCallback = localCallback; RemoteHandler = remoteHandler; ClientCertRequired = clientCertRequired; }
public UUID CreateCapability(HttpRequestCallback localHandler, bool clientCertRequired, double ttlSeconds) { UUID id = UUID.Random(); CapsRedirector redirector = new CapsRedirector(localHandler, null, clientCertRequired); lock (syncRoot) expiringCaps.Add(id, redirector, DateTime.Now + TimeSpan.FromSeconds(ttlSeconds)); return id; }
public void AddHandler(string method, string contentType, string path, bool exactPath, bool sendResponseAfterCallback, HttpRequestCallback callback) { HttpRequestSignature signature = new HttpRequestSignature(method, contentType, path, exactPath); HttpRequestHandler handler = new HttpRequestHandler(signature, callback, sendResponseAfterCallback); lock (m_handlersWriteLock) { HttpRequestHandler[] newHandlers = new HttpRequestHandler[m_requestHandlers.Length + 1]; for (int i = 0; i < m_requestHandlers.Length; i++) { newHandlers[i] = m_requestHandlers[i]; } newHandlers[m_requestHandlers.Length] = handler; m_requestHandlers = newHandlers; } }
private void DoHttpCall(ICallInfo info, HttpRequestCallback callback) { request.Callback = callback; this.PluginHost.HttpRequest(request, info); }
/// <summary> /// Set a callback to override the default 404 (Not Found) response /// </summary> /// <param name="callback">Callback that will be fired when an unhandled /// request is received, or null to reset to the default handler</param> public void Set404Handler(HttpRequestCallback callback) { _notFoundHandler = callback; }
/// <summary> /// Request for uploading a file /// </summary> /// <param name="url">requested url</param> /// <param name="httpPostData">post data</param> /// <param name="fileUploadData">file data</param> /// <param name="fileFieldName">file name in header</param> /// <param name="fileName">file name</param> /// <param name="action">call back</param> public void RequestUploadFile( string url, List<KeyValuePair<string, string>> httpPostData, byte[] fileUploadData, string fileFieldName, string fileName, HttpRequestCallback action ) { QueueItem item = new QueueItem() { Method = HttpMethod.Post, Action = action, Url = url, PostData = httpPostData, FileData = fileUploadData, FileName = fileName, FileFieldName = fileFieldName }; AddQueueItem( item ); }
void FireRequestCallback(IHttpClientContext client, IHttpRequest request, IHttpResponse response, HttpRequestCallback callback) { bool closeConnection = true; try { closeConnection = callback(client, request, response); } catch (Exception ex) { LogWriter.Write(this, LogPrio.Error, "Exception in HTTP handler: " + ex); } if (closeConnection) { try { response.Send(); } catch (Exception ex) { LogWriter.Write(this, LogPrio.Error, String.Format("Failed to send HTTP response for request to {0}: {1}", request.Uri, ex.Message)); } } }
/// <summary> /// 异步发送GET请求 /// </summary> /// <param name="url">请求的URL地址</param> /// <param name="encodingName">编码格式</param> /// <param name="timeout">超时时间 以毫秒为单位</param> /// <param name="callback">回调</param> public static void AsyncSendGetRequest(string url, string encodingName, int?timeout, HttpRequestCallback callback) { WebRequest request = null; try { // 创建HTTP请求 request = CreateHttpRequest(url, "GET", timeout); // 开始接收响应 BeginReceiveResponse(request, encodingName, callback); } finally { if (request != null) { request.Abort(); } } }
/// <summary> /// 异步发送POST请求 /// </summary> /// <param name="url">请求的URL地址</param> /// <param name="content">请求内容</param> /// <param name="encodingName">编码格式</param> /// <param name="timeout">超时时间 以毫秒为单位</param> /// <param name="callback">回调</param> public static void AsyncSendPostRequest(string url, string content, string encodingName, int?timeout, HttpRequestCallback callback) { HttpWebRequest request = null; try { // 创建HTTP请求 request = CreateHttpRequest(url, "POST", timeout); // 写入POST数据 WriteRequestContent(request, content, encodingName); // 开始接收响应 BeginReceiveResponse(request, encodingName, callback); } finally { if (request != null) { request.Abort(); } } }
void FireRequestCallback(IHttpClientContext client, IHttpRequest request, IHttpResponse response, HttpRequestCallback callback) { bool closeConnection = true; try { closeConnection = callback(client, request, response); } catch (Exception ex) { _logWriter.Write(this, LogPrio.Error, "Exception in HTTP handler: " + ex.Message); } if (closeConnection) { try { response.Send(); } catch (Exception ex) { _logWriter.Write(this, LogPrio.Error, String.Format("Failed to send HTTP response for request to {0}: {1}", request.Uri, ex.Message)); } } }
private static void BeginReceiveResponse(WebRequest request, string encodingName, HttpRequestCallback callback) { request.BeginGetResponse(EndReceiveResponse, new HttpRequestContainer { Request = request, EncodingName = encodingName, Callback = callback }); }
public void RemoveHandlers(HttpRequestCallback callback) { lock (m_handlersWriteLock) { List<HttpRequestHandler> newHandlers = new List<HttpRequestHandler>(m_requestHandlers.Length - 1); for (int i = 0; i < m_requestHandlers.Length; i++) { if (m_requestHandlers[i].Callback != callback) newHandlers.Add(m_requestHandlers[i]); } m_requestHandlers = newHandlers.ToArray(); } }
/// <summary> /// Default constructor /// </summary> /// <param name="signature">Signature pattern for matching against incoming requests</param> /// <param name="callback">Callback for handling the request</param> /// <param name="sendResponseAfterCallback">If true, the IHttpResponse will be sent /// to the client after the callback completes. Otherwise, the connection will be left /// open and the user is responsible for closing the connection later</param> public HttpRequestHandler(HttpRequestSignature signature, HttpRequestCallback callback, bool sendResponseAfterCallback) { Signature = signature; Callback = callback; SendResponseAfterCallback = sendResponseAfterCallback; }
public void AddHandler(string method, string contentType, string path, bool exactPath, bool sendResponseAfterCallback, HttpRequestCallback callback) { HttpRequestSignature signature = new HttpRequestSignature(method, contentType, path, exactPath); HttpRequestHandler handler = new HttpRequestHandler(signature, callback, sendResponseAfterCallback); lock (m_handlersWriteLock) { HttpRequestHandler[] newHandlers = new HttpRequestHandler[m_requestHandlers.Length + 1]; for (int i = 0; i < m_requestHandlers.Length; i++) newHandlers[i] = m_requestHandlers[i]; newHandlers[m_requestHandlers.Length] = handler; m_requestHandlers = newHandlers; } }
/// <summary> /// Add a request handler /// </summary> /// <param name="method">HTTP verb to match, or null to skip verb matching</param> /// <param name="contentType">Content-Type header to match, or null to skip Content-Type matching</param> /// <param name="path">Request URI path regular expression to match, or null to skip URI path matching</param> /// <param name="callback">Callback to fire when an incoming request matches the given pattern</param> /// <remarks>Using this overload, the response will automatically be sent when the callback completes</remarks> public void AddHandler(string method, string contentType, string path, HttpRequestCallback callback) { HttpRequestSignature signature = new HttpRequestSignature(method, contentType, path); AddHandler(new HttpRequestHandler(signature, callback, true)); }
/// <summary> /// Default constructor /// </summary> /// <param name="signature">Signature pattern for matching against incoming requests</param> /// <param name="callback">Callback for handling the request</param> public HttpRequestHandler(HttpRequestSignature signature, HttpRequestCallback callback) { Signature = signature; Callback = callback; }
/// <summary> /// Add a request handler /// </summary> /// <param name="method">HTTP verb to match, or null to skip verb matching</param> /// <param name="contentType">Content-Type header to match, or null to skip Content-Type matching</param> /// <param name="path">Request URI path regular expression to match, or null to skip URI path matching</param> /// <param name="sendResponseAfterCallback">If true, the IHttpResponse will be sent to the client after /// the callback completes. Otherwise, the connection will be left open and the user is responsible for /// closing the connection later</param> /// <param name="callback">Callback to fire when an incoming request matches the given pattern</param> public void AddHandler(string method, string contentType, string path, bool sendResponseAfterCallback, HttpRequestCallback callback) { HttpRequestSignature signature = new HttpRequestSignature(method, contentType, path); AddHandler(new HttpRequestHandler(signature, callback, sendResponseAfterCallback)); }
private static T HttpRequest <T>(string url, SortedDictionary <string, string> parameters, HttpRequestCallback <T> callback) { var req = WebRequest.Create(url); if (Properties.Settings.Default.UseProxy) { req.Proxy = new WebProxy(Properties.Settings.Default.ProxyHost, Properties.Settings.Default.ProxyPort); } ((HttpWebRequest)req).UserAgent = Application.ProductName + ' ' + Application.ProductVersion; byte[] data = null; if (parameters != null) { data = Encoding.ASCII.GetBytes(JoinParameters(parameters)); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = data.Length; } try { if (data != null) { using (var stream = req.GetRequestStream()) { stream.Write(data, 0, data.Length); } } return(callback(req.GetResponse())); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { using (var stream = ex.Response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { var result = reader.ReadToEnd(); // XXX:FIXME!!! 毎回メッセージボックスはウザイので別の方法が必要 MessageBox.Show(ex.Message + "\n" + result, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } return(default(T)); } catch (Exception ex) { // XXX:FIXME!!! 毎回メッセージボックスはウザイので別の方法が必要 MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); return(default(T)); } }