internal void GotResponse(IAsyncResult result) { try { response = (HttpWebResponse)request?.EndGetResponse(result); Success = true; } catch (WebException we) { // If we don't get a response, let the exception bubble up as we can't do anything if (we.Response == null) { var defaultResponse = CreateDefaultResponseForError(we); callback?.Invoke(defaultResponse); return; } //Anything that doesn't return error 200 throws an exception. Sucks. :l response = (HttpWebResponse)we.Response; //TODO: Handle timeouts, etc? } catch (Exception e) { var defaultResponse = CreateDefaultResponseForError(e); callback?.Invoke(defaultResponse); return; } K responseObj; if (response == null) { responseObj = CreateDefaultResponseForError(new Exception("Empty response")); callback?.Invoke(responseObj); return; } try { using (Stream responseReading = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseReading)) { string responseData = reader.ReadToEnd(); responseObj = responseData.Deserialize <K>(); } } catch (Exception e) { responseObj = CreateDefaultResponseForError(e); } callback?.Invoke(responseObj); }
private void BeginRequest(HttpWebRequest request, System.Action<HttpResult> onResult) { //int total = 0; //byte[] buffer = new byte[1000]; request.BeginGetResponse(new AsyncCallback((result) => { var data = request.EndGetResponse(result); HttpResult r = new HttpResult(); try { var stream = new StreamReader(data.GetResponseStream()); r.response = stream.ReadToEnd(); stream.Close(); //TODO:!! /*stream.BeginRead(buffer, 0, 1000, new AsyncCallback((read) => { var r = stream.EndRead(read); if (r == 0) { //TODO: !! } else { //stream.BeginRead } }));*/ } catch (Exception ex) { r.errDescr = ex.Message; } finally { data.Close(); } if (onResult != null) { onResult(r); } }), null); }
public static IObservable <HttpWebResponse> GetResponseObservableAsync(this HttpWebRequest request) { HttpWebRequest httpWebRequest = request; return(AbortableDeferredAsyncRequest(((WebRequest)httpWebRequest).BeginGetResponse, (IAsyncResult ar) => (HttpWebResponse)request.EndGetResponse(ar), request)); }
public void Button2_Click(object sender, EventArgs e) { XmlDocument soapEnvelopeXml = CreateSoapEnvelope(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://web27.agency2000.co.il/Test/TestService.asmx?op=SuppliersGain"); request.Headers.Add("SOAP:Action"); request.ContentType = "text/xml;charset=\"utf-8\""; request.Method = "POST"; using (Stream stream = request.GetRequestStream()) { soapEnvelopeXml.Save(stream); } IAsyncResult asyncResult = request.BeginGetResponse(null, null); asyncResult.AsyncWaitHandle.WaitOne(); string soapResult; SupplierGain[] supplierGains = new SupplierGain[3]; supplierGains[0] = new SupplierGain(); supplierGains[1] = new SupplierGain(); supplierGains[2] = new SupplierGain(); using (WebResponse webResponse = request.EndGetResponse(asyncResult)) { using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); } int i = 0; int index = 0; i = soapResult.IndexOf("Name"); while (i != -1) { string a = ""; string temp = ""; while (a != "<") { i++; temp += a; a = soapResult[i + 4].ToString(); } supplierGains[index].Name = temp; soapResult = soapResult.Substring(soapResult.IndexOf('N') + 15); i = soapResult.IndexOf("TotalGain"); a = ""; temp = ""; while (a != "<") { i++; temp += a; a = soapResult[i + 9].ToString(); } supplierGains[index].TotalGain = Convert.ToDecimal(temp); soapResult = soapResult.Substring(soapResult.IndexOf('T') + 30); i = soapResult.IndexOf("Name"); index++; } } Label2.Text = "Supplier 1 - Name:" + supplierGains[0].Name + ", " + "Total gain:" + supplierGains[0].TotalGain; Label3.Text = "Supplier 2 - Name:" + supplierGains[1].Name + ", " + "Total gain:" + supplierGains[1].TotalGain; Label4.Text = "Supplier 3 - Name:" + supplierGains[2].Name + ", " + "Total gain:" + supplierGains[2].TotalGain; }
private void OnGetResponse(IAsyncResult ar) { try { requestIsTerminating = true; // grab the custom state object WebRequestState state = (WebRequestState)ar.AsyncState; HttpWebRequest request = (HttpWebRequest)state.WebRequest; HttpWebResponse resp = null; if (request.HaveResponse) { // TODO, its crashing mostly here // get the Response try { resp = (HttpWebResponse)request.EndGetResponse(ar); } catch (WebException ex) { activeRequests--; requestIsTerminating = false; if (ex.Response == null) { StartWebRequest(); } else { HttpWebResponse res = ex.Response as HttpWebResponse; if (res.StatusCode == HttpStatusCode.NotFound) { TerminateBoshSession(); } } return; } // The server must always return a 200 response code, // sending any session errors as specially-formatted identifiers. if (resp.StatusCode != HttpStatusCode.OK) { activeRequests--; requestIsTerminating = false; if (resp.StatusCode == HttpStatusCode.NotFound) { //Console.WriteLine("Not Found"); TerminateBoshSession(); } return; } } else { //Console.WriteLine("No response"); } Stream rs = resp.GetResponseStream(); int readlen; byte[] readbuf = new byte[1024]; MemoryStream ms = new MemoryStream(); while ((readlen = rs.Read(readbuf, 0, readbuf.Length)) > 0) { ms.Write(readbuf, 0, readlen); } byte[] recv = ms.ToArray(); if (recv.Length > 0) { string sbody = null; string stanzas = null; ParseResponse(Encoding.UTF8.GetString(recv, 0, recv.Length), ref sbody, ref stanzas); if (stanzas != null) { byte[] bStanzas = Encoding.UTF8.GetBytes(stanzas); base.FireOnReceive(bStanzas, bStanzas.Length); } else { if (sbody != null) { var doc = new Document(); doc.LoadXml(sbody); if (doc.RootElement != null) { var body = doc.RootElement as Body; if (body.Type == BoshType.terminate) { TerminateBoshSession(); } } } if (terminate && !terminated) { // empty teminate response TerminateBoshSession(); } } } // cleanup webrequest resources ms.Close(); rs.Close(); resp.Close(); activeRequests--; requestIsTerminating = false; //if (activeRequests == 0 && !terminated) if ((activeRequests == 0 && !terminated) || (activeRequests == 1 && m_SendQueue.Count > 0)) { StartWebRequest(); } } catch (Exception ex) { } }
private static void CheckSocketConnect <T>(object internetState) { lock (_internetCheckLock) { isInternetCheckRunning = true; } HttpWebRequest myRequest = null; Action <bool> callback = null; Action <PubnubClientError> errorCallback = null; string[] channels = null; string[] channelGroups = null; try { InternetState <T> state = internetState as InternetState <T>; if (state != null) { callback = state.Callback; errorCallback = state.ErrorCallback; channels = state.Channels; channelGroups = state.ChannelGroups; } mreSocketAsync = new ManualResetEvent(false); myRequest = (HttpWebRequest)System.Net.WebRequest.Create("https://pubsub.pubnub.com/time/0"); myRequest.BeginGetResponse(cb => { try { using (HttpWebResponse resp = myRequest.EndGetResponse(cb) as HttpWebResponse) { if (resp != null && resp.StatusCode == HttpStatusCode.OK) { LoggingMethod.WriteToLog(string.Format("DateTime {0} CheckSocketConnect Resp {1}", DateTime.Now.ToString(), HttpStatusCode.OK.ToString()), LoggingMethod.LevelInfo); _status = true; } } } catch (Exception ex) { _status = false; ParseCheckSocketConnectException <T>(ex, channels, channelGroups, errorCallback, callback); LoggingMethod.WriteToLog(string.Format("DateTime {0} CheckSocketConnect Failed {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelInfo); } finally { mreSocketAsync.Set(); } }, null); mreSocketAsync.WaitOne(330); } catch (Exception ex) { _status = false; ParseCheckSocketConnectException <T>(ex, channels, channelGroups, errorCallback, callback); } finally { isInternetCheckRunning = false; mres.Set(); } }
private static void GetResponseCallback <T>(IAsyncResult asynchronousResult) { RequestState <T> requestState = (RequestState <T>)asynchronousResult.AsyncState; T result = default(T); try { HttpWebRequest request = requestState.Request; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader responseReader = new StreamReader(responseStream, System.Text.Encoding.UTF8)) { string responseJsonString = responseReader.ReadToEnd(); if ((requestState.Api >= Api.COUNTERSERVICE_GET && requestState.Api <= Api.COUNTERSERVICE_COM_SET) || requestState.Api == Api.CACHESERVICE_CONTAINS) { result = (T)Convert.ChangeType(responseJsonString, typeof(T)); } else { if (string.IsNullOrEmpty(responseJsonString) == false) { result = JsonMapper.ToObject <T>(responseJsonString); } } } } response.Close(); if (requestState.Callback != null) { requestState.Callback.ResponseHandler.Invoke(result); } } catch (WebException ex) { using (Stream responseStream = ex.Response.GetResponseStream()) { using (StreamReader responseReader = new StreamReader(responseStream, System.Text.Encoding.UTF8)) { string responseJsonString = responseReader.ReadToEnd(); BackendlessFault fault = null; try { JsonData errorResponse = JsonMapper.ToObject(responseJsonString); int code = (int)errorResponse["code"]; string message = (string)errorResponse["message"]; fault = new BackendlessFault(code.ToString(), message, null); } catch (System.Exception) { fault = new BackendlessFault(ex); } if (requestState.Callback != null) { requestState.Callback.ErrorHandler.Invoke(fault); } } } } catch (System.Exception ex) { BackendlessFault backendlessFault = new BackendlessFault(ex); if (requestState.Callback != null) { requestState.Callback.ErrorHandler.Invoke(backendlessFault); } } }
internal static void GetToken(SocialType type, ClientInfo client, string code, Action <AccessToken> action) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GetTokenUrl(type, client, code)); httpWebRequest.Method = "POST"; if (type == SocialType.Douban) { post_param = "client_id=" + client.ClientId + "&client_secret=" + client.ClientSecret + "&redirect_uri=" + HttpUtility.UrlEncode(client.RedirectUri) + "&grant_type=authorization_code&" + code; httpWebRequest.BeginGetRequestStream(new AsyncCallback(ReadCallback), httpWebRequest); allDone.WaitOne(); } httpWebRequest.BeginGetResponse((p) => { HttpWebRequest request = (HttpWebRequest)p.AsyncState; HttpWebResponse httpWebResponse; try { httpWebResponse = (HttpWebResponse)request.EndGetResponse(p); } catch (WebException ex) { return; } if (httpWebResponse != null) { using (var stream = httpWebResponse.GetResponseStream()) { AccessToken token = new AccessToken(); if (type == SocialType.Tencent) { using (var reader = new System.IO.StreamReader(stream)) { string text = reader.ReadToEnd(); if (!string.IsNullOrEmpty(text)) { //access_token=ec70e646177f025591e4282946c19b67&expires_in=604800&name=xshf12345 var acc = text.Split('&'); foreach (var item in acc) { var single = item.Split('='); if (single[0] == "access_token") { token.Token = single[1]; } else if (single[0] == "expires_in") { token.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToInt32(single[1])); } else if (single[0] == "name") { token.UserInfo = single[1]; } } token.OpenId = client.Tag; } } } else if (type == SocialType.Weibo) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Weibo.WeiboAccessToken)); var item = ser.ReadObject(stream) as Weibo.WeiboAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.uid; } else if (type == SocialType.Renren) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Renren.RenrenAccessToken)); var item = ser.ReadObject(stream) as Renren.RenrenAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.user.name; } else if (type == SocialType.Douban) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Douban.DoubanAccessToken)); var item = ser.ReadObject(stream) as Douban.DoubanAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.douban_user_id; } else if (type == SocialType.Fanfou) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Fanfou.FanfouAccessToken)); var item = ser.ReadObject(stream) as Fanfou.FanfouAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.user_id; } action(token); string filePath = string.Format(SocialAPI.ACCESS_TOKEN_PREFIX, type.ToString()); JsonHelper.SerializeData <AccessToken>(filePath, token); } } }, httpWebRequest); }
// Metodo per gestire la chiamata al Webservice, prende in input una istanza di classe(fra quelle del modello) e restituisce un oggetto di tipo InforResult public static InforResult CallWebService <T>(T reportRequest) { //var _url = "http://192.168.1.31:8312/c4ws/services/IWMStdReportProduction/lntestclone"; //var _url = "http://192.168.1.31:8312/c4ws/services/IWMStdUnplannedMatlIssue/lntestclone?wsdl"; //var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld"; var _action = ""; Dictionary <string, string> addressList = new Dictionary <string, string>(); var resultAddress = ReadConfigFile(out addressList); string _url = string.Empty; if (resultAddress.InforCallSucceeded == false) { return(resultAddress); } try { KeyValuePair <string, string> methodToCall; if (reportRequest is List <UnplannedMat> ) { methodToCall = addressList.FirstOrDefault(x => x.Key.Contains("UnplannedMat")); } else { methodToCall = addressList.FirstOrDefault(x => x.Key.Contains(reportRequest.GetType().Name)); } if ((methodToCall.Key != null) && (methodToCall.Value != null)) { _url = methodToCall.Value; } else { return(new InforResult(false, "CallWebService: Metodo non trovato")); } } catch (InvalidOperationException ex) { return(new InforResult(false, "CallWebService: " + ex.Message)); } catch (ArgumentNullException ex) { return(new InforResult(false, "CallWebService: " + ex.Message)); } var resultCreateEnvelope = new InforResult(); string erpOrder = string.Empty; XmlDocument soapEnvelopeXml = CreateSoapEnvelope(reportRequest, out resultCreateEnvelope); if (resultCreateEnvelope.InforCallSucceeded == false) { return(resultCreateEnvelope); } InforResult createWebRequestResult = new InforResult(); HttpWebRequest webRequest = CreateWebRequest(_url, _action, out createWebRequestResult); if (createWebRequestResult.InforCallSucceeded == false) { return(createWebRequestResult); } var insertResult = InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest); if (insertResult.InforCallSucceeded == false) { return(insertResult); } // begin async call to web request. IAsyncResult asyncResult = null; try { asyncResult = webRequest.BeginGetResponse(null, null); } catch (WebException ex) { if (ex.InnerException != null) { return(new InforResult(false, "BeginGetResponse: " + ex.InnerException.ToString())); } else if (ex.Message != null) { return(new InforResult(false, ex.Message)); } return(new InforResult(false, "BeginGetResponse: Errore nella BeginGetResponse")); } catch (Exception ex) { if (ex.InnerException != null) { return(new InforResult(false, "BeginGetResponse: " + ex.InnerException.ToString())); } else if (ex.Message != null) { return(new InforResult(false, "BeginGetResponse: " + ex.Message)); } return(new InforResult(false, "Errore nella BeginGetResponse")); } // suspend this thread until call is complete. You might want to // do something usefull here like update your UI. try { asyncResult.AsyncWaitHandle.WaitOne(); } catch (Exception ex) { return(new InforResult(false, "AsyncWaitHandle: " + ex.Message)); } // get the response from the completed web request. try { using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) { try { InforResult webResponseResult = ParseWebResponse(webResponse, reportRequest); return(webResponseResult); } catch (Exception ex) { return(new InforResult(false, "ParseWebResponse: " + ex.Message)); } } } catch (FaultException ex) { MessageFault msgFault = ex.CreateMessageFault(); return(new InforResult(true, "EndGetResponse: " + ex.Message)); } catch (WebException ex) { string exMessage = ex.Message; if (ex.Response != null) { using (StreamReader responseReader = new StreamReader(ex.Response.GetResponseStream())) { exMessage = responseReader.ReadToEnd(); if (exMessage.Contains("faultstring")) { var doc = XDocument.Parse(exMessage); exMessage = doc.Root.Descendants("faultstring").First().Value; } } } return(new InforResult(false, "EndGetResponse: " + exMessage)); } //return new InforResult(true, "Chiamata eseguita con successo!"); }
/*public static async Task<string> DownloadStringAsync(string url) * { * if (!HasInternet()) * return null; * * var tcs = new TaskCompletionSource<string>(); * try * { * using (var client = new WebClient()) * { * client.DownloadStringCompleted += (s, e) => * { * if (e.Error != null) * tcs.TrySetException(e.Error); * else * if (e.Cancelled) * tcs.TrySetCanceled(); * else * tcs.TrySetResult(e.Result); * }; * client.DownloadStringAsync(new Uri(url)); * } * return await tcs.Task; * } * catch (Exception ex) * { * Relatório.ExHandler(ex); * return null; * } * }*/ public static async Task <bool> DownloadFileAsync(string url, string local) { if (!HasInternet()) { return(false); } HttpWebRequest get = (HttpWebRequest)WebRequest.Create(url); get.Method = WebRequestMethods.Http.Get; var tcs = new TaskCompletionSource <WebResponse>(); try { get.BeginGetResponse(iar => { try { tcs.TrySetResult(get.EndGetResponse(iar)); } catch (OperationCanceledException) { tcs.TrySetCanceled(); } catch (Exception ex) { tcs.TrySetException(ex); } }, null); using (WebResponse response = await tcs.Task) { using (Stream rs = response.GetResponseStream()) { int bytesRead = 0; byte[] buffer = new byte[4096]; MemoryStream ms = new MemoryStream(); while ((bytesRead = rs.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, bytesRead); } ms.Position = 0; var md5 = MD5.Create(); byte[] localHash = new byte[16]; byte[] remoteHash = md5.ComputeHash(ms); if (File.Exists(local)) { using (FileStream fs = new FileStream(local, FileMode.Open, FileAccess.Read, FileShare.Read)) localHash = md5.ComputeHash(fs); } if (!remoteHash.SequenceEqual(localHash)) { ms.Position = 0; using (FileStream fs = new FileStream(local, FileMode.Create, FileAccess.Write, FileShare.Read)) while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, bytesRead); } } } } return(true); } catch (Exception ex) { Relatório.ExHandler(ex); return(false); } }
private void ServicesReceived(IAsyncResult result) { HttpWebResponse response = null; try { int abortCount = 0; int bytesRead = 0; byte[] buffer = new byte[10240]; StringBuilder servicesXml = new StringBuilder(); XmlDocument xmldoc = new XmlDocument(); HttpWebRequest request = result.AsyncState as HttpWebRequest; response = request.EndGetResponse(result) as HttpWebResponse; Stream s = response.GetResponseStream(); if (response.StatusCode != HttpStatusCode.OK) { NatUtility.Log("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode); return; // FIXME: This the best thing to do?? } while (true) { bytesRead = s.Read(buffer, 0, buffer.Length); servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead)); try { xmldoc.LoadXml(servicesXml.ToString()); response.Close(); break; } catch (XmlException) { // If we can't receive the entire XML within 500ms, then drop the connection // Unfortunately not all routers supply a valid ContentLength (mine doesn't) // so this hack is needed to keep testing our recieved data until it gets successfully // parsed by the xmldoc. Without this, the code will never pick up my router. if (abortCount++ > 50) { response.Close(); return; } NatUtility.Log("{0}: Couldn't parse services list", HostEndPoint); System.Threading.Thread.Sleep(10); } } NatUtility.Log("{0}: Parsed services list", HostEndPoint); XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable); ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0"); XmlNodeList nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns); foreach (XmlNode node in nodes) { //Go through each service there foreach (XmlNode service in node.ChildNodes) { //If the service is a WANIPConnection, then we have what we want string type = service["serviceType"].InnerText; NatUtility.Log("{0}: Found service: {1}", HostEndPoint, type); StringComparison c = StringComparison.OrdinalIgnoreCase; if (type.Equals(this.serviceType, c)) { this.controlUrl = service["controlURL"].InnerText; NatUtility.Log("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl); try { Uri u = new Uri(controlUrl); if (u.IsAbsoluteUri) { EndPoint old = hostEndPoint; this.hostEndPoint = new IPEndPoint(IPAddress.Parse(u.Host), u.Port); NatUtility.Log("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint); this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length); NatUtility.Log("{0}: New control url: {1}", HostEndPoint, controlUrl); } } catch { NatUtility.Log("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl); } NatUtility.Log("{0}: Handshake Complete", HostEndPoint); this.callback(this); return; } } } //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding //So we don't invoke the callback, so this device is never added to our lists } catch (WebException ex) { // Just drop the connection, FIXME: Should i retry? NatUtility.Log("{0}: Device denied the connection attempt: {1}", HostEndPoint, ex); } finally { if (response != null) { response.Close(); } } }
public string SendRequest(string sRequest, out string sError, CookieCollection oCookies = null) { // Send the request and return the response _requestName = ClassLogger.ReadMethodFromRequest(sRequest); sError = ""; if (String.IsNullOrEmpty(_targetURL)) { sError = "No target server specified"; return(""); } string sResponse = ""; SecurityProtocolType currentSecurityProtocol = ServicePointManager.SecurityProtocol; ServicePointManager.SecurityProtocol = _securityProtocol; HttpWebRequest oWebRequest = null; try { oWebRequest = (HttpWebRequest)WebRequest.Create(_targetURL); } catch (Exception ex) { sError = ex.Message; return(""); } oWebRequest.UserAgent = String.Format("{1}/{0}", Application.ProductVersion, Application.ProductName); if (_bypassWebProxy) { oWebRequest.Proxy = null; } // Set authentication _credentialHandler.ApplyCredentialsToHttpWebRequest(oWebRequest); _credentialHandler.LogCredentials(_logger); oWebRequest.ContentType = "text/xml;charset=\"utf-8\""; oWebRequest.Accept = "text/xml"; if (_httpHeaders.Count > 0) { foreach (string[] header in _httpHeaders) { try { switch (header[0].ToLower()) { case "user-agent": oWebRequest.UserAgent = header[1]; break; case "content-type": oWebRequest.ContentType = header[1]; break; case "accept": oWebRequest.Accept = header[1]; break; default: oWebRequest.Headers[header[0]] = header[1]; break; } } catch { } } } // We add a client-request-id header so that we can easily match request/response string clientRequestId = oWebRequest.Headers.Get("client-request-id"); if (String.IsNullOrEmpty(clientRequestId)) { clientRequestId = Guid.NewGuid().ToString(); oWebRequest.Headers["client-request-id"] = clientRequestId; } StringBuilder sTimings = new StringBuilder(); sTimings.AppendLine("Latency (latency shown in milliseconds, times are in ticks)").AppendLine(); sTimings.AppendLine($"client-request-id: {clientRequestId}").AppendLine(); if (String.IsNullOrEmpty(oWebRequest.Headers.Get("return-client-request-id"))) { oWebRequest.Headers["return-client-request-id"] = "true"; } oWebRequest.Method = "POST"; XmlDocument oSOAPRequest = new XmlDocument(); if (!String.IsNullOrEmpty(sRequest)) { try { oSOAPRequest.LoadXml(sRequest); } catch (Exception ex) { sError = ex.Message; sResponse = "Request was invalid XML (not sent): " + ex.Message + "\n\r\n\r" + sRequest; Log(sResponse, "Response"); return(""); } } oWebRequest.CookieContainer = new CookieContainer(); if (!(oCookies == null)) { // Add cookies to the request foreach (Cookie oCookie in oCookies) { try { oWebRequest.CookieContainer.Add(oCookie); } catch { } } LogCookies(oCookies, "Request Cookies"); } LogSSLSettings(); Stream stream = null; try { stream = oWebRequest.GetRequestStream(); } catch (Exception ex) { // Failed to send request sError = ex.Message; sResponse = "Error occurred: " + ex.Message + "\n\r\n\r"; } if (stream == null) { // Failed to obtain request stream if (String.IsNullOrEmpty(sError)) { sError = "Failed to open connection"; } if (!String.IsNullOrEmpty(sResponse)) { Log(sResponse, "Response"); } return(""); } DateTime requestSendStartTime = DateTime.Now; if (!string.IsNullOrEmpty(sRequest)) { oSOAPRequest.Save(stream); } stream.Close(); DateTime requestSendEndTime = DateTime.Now; LogHeaders(oWebRequest.Headers, "Request Headers", _targetURL); Log(oSOAPRequest.OuterXml, "Request", clientRequestId); oWebRequest.Expect = ""; DateTime responseReceiveEndTime = DateTime.MinValue; DateTime responseReceiveStartTime = DateTime.Now; IAsyncResult asyncResult = oWebRequest.BeginGetResponse(null, null); asyncResult.AsyncWaitHandle.WaitOne(); WebResponse oWebResponse = null; try { oWebResponse = oWebRequest.EndGetResponse(asyncResult); responseReceiveEndTime = DateTime.Now; _lastResponseHeaders = oWebResponse.Headers; LogHeaders(oWebResponse.Headers, "Response Headers", "", (oWebResponse as HttpWebResponse)); _responseCookies = (oWebResponse as HttpWebResponse).Cookies; LogCookies(_responseCookies, "Response Cookies"); } catch (Exception ex) { responseReceiveEndTime = DateTime.Now; if (ex is WebException) { WebException wex = ex as WebException; sError = wex.Message; if (!(wex.Response == null)) { using (StreamReader oReader = new StreamReader(wex.Response.GetResponseStream())) { sResponse = oReader.ReadToEnd(); } _lastResponseHeaders = wex.Response.Headers; LogHeaders(wex.Response.Headers, "Response Headers", "", (wex.Response as HttpWebResponse)); } } else { sError = ex.Message; } } try { using (StreamReader oReader = new StreamReader(oWebResponse.GetResponseStream())) { sResponse += oReader.ReadToEnd(); } } catch { } try { oWebResponse.Close(); } catch { } Log(sResponse, "Response", clientRequestId); sTimings.AppendLine($"Request start: {(long)(requestSendStartTime.Ticks/10000)}"); sTimings.AppendLine($"Request complete: {(long)(requestSendEndTime.Ticks/10000)}"); sTimings.AppendLine($"Request latency: {(long)((requestSendEndTime.Ticks- requestSendStartTime.Ticks) / 10000)}").AppendLine(); sTimings.AppendLine($"Response start: {(long)(responseReceiveStartTime.Ticks / 10000)}"); sTimings.AppendLine($"Response complete: {(long)(responseReceiveEndTime.Ticks / 10000)}"); sTimings.AppendLine($"Response latency: {(long)((responseReceiveEndTime.Ticks - responseReceiveStartTime.Ticks) / 10000)}").AppendLine(); sTimings.AppendLine($"Total time taken (includes processing time): {(long)((responseReceiveEndTime.Ticks - requestSendStartTime.Ticks) / 10000)}"); Log(sTimings.ToString(), "Latency Report"); return(sResponse); }
private void GetUrlCallback(IAsyncResult result) { if (result == null || result.AsyncState == null) { return; } HttpWebRequest request = result.AsyncState as HttpWebRequest; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); using (Stream stream = response.GetResponseStream()) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); string responseString = ""; string line; while ((line = reader.ReadLine()) != null) { responseString += line; } HttpStatusCode statusCode = response.StatusCode; // If status between 200 and 300, success if (statusCode >= HttpStatusCode.OK && statusCode < HttpStatusCode.MultipleChoices) { JToken root = JObject.Parse(responseString); JToken successToken = root["success"]; bool success = successToken.ToString().ToLower().Equals("true"); if (success) { if (parameters.matResponse != null) { parameters.matResponse.DidSucceedWithData(responseString); } // Get site_event_type from json response JToken siteEventTypeToken = root["site_event_type"]; string siteEventType = siteEventTypeToken.ToString(); // Only store log_id for opens if (siteEventType.Equals("open")) { JToken logIdToken = root["log_id"]; string logId = logIdToken.ToString(); if (parameters.OpenLogId == null) { parameters.OpenLogId = logId; } parameters.LastOpenLogId = logId; } } else { if (parameters.matResponse != null) { parameters.matResponse.DidFailWithError(responseString); } if (currentUrlAttempt < MAX_NUMBER_OF_RETRY_ATTEMPTS) { Debug.WriteLine("MAT request failed, will be queued"); eventQueue.AddToQueue(currentUrl, ++currentUrlAttempt); } else { Debug.WriteLine("Exceeded maximum number of retries. Will not be requeued."); } } if (parameters.DebugMode) { Debug.WriteLine("Server response is " + responseString); } } else // Requeue all other requests { if (currentUrlAttempt < MAX_NUMBER_OF_RETRY_ATTEMPTS) { Debug.WriteLine("MAT request failed, will be queued"); eventQueue.AddToQueue(currentUrl, ++currentUrlAttempt); } else { Debug.WriteLine("Exceeded maximum number of retries. Will not be requeued."); } } } } catch (WebException e) { Debug.WriteLine(e.Message); // Requeue the request for SSL error // Have to convert to String because TrustFailure isn't accessible in this .NET WebExceptionStatus for some reason if (e.Status.ToString().Equals("TrustFailure")) { if (currentUrlAttempt < MAX_NUMBER_OF_RETRY_ATTEMPTS) { Debug.WriteLine("SSL error, will be queued"); eventQueue.AddToQueue(currentUrl, ++currentUrlAttempt); } else { Debug.WriteLine("Exceeded maximum number of retries. Will not be requeued."); } return; } //For 400 (HttpWebRequest throws WebException on 4XX-5XX, so the logic must be written here) //We may want to switch to HttpClient for Windows Phone 8, but this requires downloading a separate library (still in beta, last I checked). //Within WebException is the only way to provide feedback to the client. if (e.Response != null) { using (WebResponse webResponse = e.Response) { HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse; using (Stream stream = webResponse.GetResponseStream()) using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8)) { string responseString = ""; string line; while ((line = streamReader.ReadLine()) != null) { responseString += line; } if (httpWebResponse.StatusCode == HttpStatusCode.BadRequest && webResponse.Headers["X-MAT-Responder"] != null) { if (parameters.matResponse != null) { parameters.matResponse.DidFailWithError((responseString)); } Debug.WriteLine("MAT request received 400 error from server, won't be retried"); } else //Requeue for any other status code { if (parameters.matResponse != null) { parameters.matResponse.DidFailWithError((responseString)); } if (currentUrlAttempt < MAX_NUMBER_OF_RETRY_ATTEMPTS) { Debug.WriteLine("MAT request failed, will be queued"); eventQueue.AddToQueue(currentUrl, ++currentUrlAttempt); } else { Debug.WriteLine("Exceeded maximum number of retries. Will not be requeued."); } } } } } } }
async Task <string> SendRequestAndGetJsonResponseClassicHttpWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseClassicHttpWithPOST", DateTime.Now.ToString()), pubnubConfig.LogVerbosity); var taskComplete = new TaskCompletionSource <string>(); try { request.Method = "POST"; request.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes(postData); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); #if !NET35 && !NET40 && !NET45 && !NET461 using (var requestStream = await Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, pubnubRequestState)) { requestStream.Write(data, 0, data.Length); requestStream.Flush(); } #else using (var requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); requestStream.Flush(); } #endif IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback( (asynchronousResult) => { RequestState <T> asyncRequestState = asynchronousResult.AsyncState as RequestState <T>; HttpWebRequest asyncWebRequest = asyncRequestState.Request as HttpWebRequest; if (asyncWebRequest != null) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before EndGetResponse With POST ", DateTime.Now.ToString())); HttpWebResponse asyncWebResponse = (HttpWebResponse)asyncWebRequest.EndGetResponse(asynchronousResult); stopWatch.Stop(); if (pubnubTelemetryMgr != null) { pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } asyncRequestState.Response = asyncWebResponse; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, After EndGetResponse With POST ", DateTime.Now.ToString())); using (StreamReader streamReader = new StreamReader(asyncWebResponse.GetResponseStream())) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Inside StreamReader With POST ", DateTime.Now.ToString())); //Need to return this response string jsonString = streamReader.ReadToEnd(); asyncRequestState.GotJsonResponse = true; System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST ", DateTime.Now.ToString())); taskComplete.TrySetResult(jsonString); } if (asyncRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif asyncRequestState.Response = null; asyncRequestState.Request = null; } } } ), pubnubRequestState); Timer webRequestTimer = new Timer(OnPubnubWebRequestTimeout <T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); return(taskComplete.Task.Result); } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 await Task.Factory.StartNew(() => { }); string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST from WebException response", DateTime.Now.ToString())); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { taskComplete.TrySetException(ex); } return(""); } catch (Exception ex) { taskComplete.TrySetException(ex); return(""); } }
async Task <string> SendRequestAndGetJsonResponseTaskFactory <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request) { HttpWebResponse response = null; LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseTaskFactory", DateTime.Now.ToString()), pubnubConfig.LogVerbosity); try { request.Method = (pubnubRequestState != null && pubnubRequestState.ResponseType == PNOperationType.PNDeleteMessageOperation) ? "DELETE" : "GET"; Timer webRequestTimer = new Timer(OnPubnubWebRequestTimeout <T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); response = await Task.Factory.FromAsync <HttpWebResponse>(request.BeginGetResponse, asyncPubnubResult => (HttpWebResponse)request.EndGetResponse(asyncPubnubResult), pubnubRequestState); stopWatch.Stop(); if (pubnubConfig.EnableTelemetry && pubnubTelemetryMgr != null) { pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } pubnubRequestState.Response = response; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got PubnubWebResponse for {1}", DateTime.Now.ToString(), request.RequestUri.ToString())); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); pubnubRequestState.GotJsonResponse = true; System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON", DateTime.Now.ToString())); if (pubnubRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif pubnubRequestState.Response = null; pubnubRequestState.Request = null; } return(jsonString); } } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON from WebException response", DateTime.Now.ToString())); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { throw ex; } return(""); } catch (Exception ex) { throw ex; } }
private async void _getLogisticChannelCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); string resultContent = string.Empty; using (var reader = new StreamReader(response.GetResponseStream())) { resultContent = reader.ReadToEnd(); }; if (!string.IsNullOrEmpty(resultContent)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { try { var dumpJson = Newtonsoft.Json.JsonConvert.DeserializeObject <ErrorMessage>(resultContent); if (dumpJson.error != null && dumpJson.err_message != null) { if (!string.IsNullOrEmpty(dumpJson.error)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await new MessageDialog(StaticResources.choosingLanguage.GlobalWarningSession).ShowAsync(); StaticResources.NavigationFrame.Navigate(typeof(ShopeeLoginPage), null, new DrillInNavigationTransitionInfo()); StaticResources.isLoginPage = true; }); } return; } var dumpJson2 = Newtonsoft.Json.JsonConvert.DeserializeObject <ErrorMessage2>(resultContent); if (dumpJson2.errcode != null && dumpJson2.message != null) { if (!string.IsNullOrEmpty(dumpJson2.errcode)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await new MessageDialog(StaticResources.choosingLanguage.GlobalWarningSession).ShowAsync(); StaticResources.NavigationFrame.Navigate(typeof(ShopeeLoginPage), null, new DrillInNavigationTransitionInfo()); StaticResources.isLoginPage = true; }); } return; } } catch { } var dumpjson = Newtonsoft.Json.JsonConvert.DeserializeObject <LogisticsChannels>(resultContent); this.ListLogisticSize = dumpjson.logistics_sizes; var listChannel = new ObservableCollection <LogisticsChannel>(dumpjson.logistics_channels.Where(p => p.enabled == 1).ToList()); if (listChannel.Count() != this.ListLogisticsChannelClone.Count()) { foreach (var channel in listChannel) { LogisticsChannelClone channelClone = new LogisticsChannelClone(); if (double.Parse(channel.price) > 0) { channel.supported = true; } this.CloneLogisticChannel(channel, channelClone, this.ListLogisticSize); this.ListLogisticsChannelClone.Add(channelClone); } } }); } } catch (WebException ex) { try { using (var streamReader = new StreamReader(ex.Response.GetResponseStream())) { var resp = streamReader.ReadToEnd(); var dumpJson = Newtonsoft.Json.JsonConvert.DeserializeObject <ErrorMessage>(resp); if (dumpJson.error != null && dumpJson.err_message != null) { if (!string.IsNullOrEmpty(dumpJson.error)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { StaticResources.SelectedShopLogin.ShopStatus = "Out of date"; await new MessageDialog(StaticResources.choosingLanguage.GlobalWarningSession).ShowAsync(); StaticResources.NavigationFrame.Navigate(typeof(ShopeeLoginPage), null, new DrillInNavigationTransitionInfo()); StaticResources.isLoginPage = true; }); } return; } var dumpJson2 = Newtonsoft.Json.JsonConvert.DeserializeObject <ErrorMessage2>(resp); if (dumpJson2.errcode != null && dumpJson2.message != null) { if (!string.IsNullOrEmpty(dumpJson2.errcode)) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { StaticResources.SelectedShopLogin.ShopStatus = "Out of date"; await new MessageDialog(StaticResources.choosingLanguage.GlobalWarningSession).ShowAsync(); StaticResources.NavigationFrame.Navigate(typeof(ShopeeLoginPage), null, new DrillInNavigationTransitionInfo()); StaticResources.isLoginPage = true; }); } return; } } } catch (Exception) { } } }
private AsyncCallCompletedEventArgs CreateEventArgsForRequest(IAsyncResult asyncResult) { IdsException exception = null; AsyncCallCompletedEventArgs resultArguments = null; byte[] receiveBytes = new byte[0]; bool isResponsePdf = false; // Get the async state of the web request. HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; // Invoke the end method of the asynchronous call. HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); string resultString = string.Empty; if (!string.IsNullOrWhiteSpace(response.ContentEncoding) && this.ResponseCompressor != null) { using (var responseStream = response.GetResponseStream()) { using (var decompressedStream = this.ResponseCompressor.Decompress(responseStream)) { if (response.ContentType.ToLower().Contains(CoreConstants.CONTENTTYPE_APPLICATIONPDF.ToLower())) { receiveBytes = ConvertResponseStreamToBytes(decompressedStream); isResponsePdf = true; } else { // Get the response stream. StreamReader reader = new StreamReader(decompressedStream); // Read the Stream resultString = reader.ReadToEnd(); // Close reader reader.Close(); } } } } else { using (Stream responseStream = response.GetResponseStream()) { //get the response in bytes if the conten-type is application/pdf if (response.ContentType.ToLower().Contains(CoreConstants.CONTENTTYPE_APPLICATIONPDF.ToLower())) { receiveBytes = ConvertResponseStreamToBytes(responseStream); isResponsePdf = true; } else { // Get the response stream. StreamReader reader = new StreamReader(responseStream); // Read the Stream resultString = reader.ReadToEnd(); // Close reader reader.Close(); } } } // Log response to disk. this.RequestLogging.LogPlatformRequests(resultString, false); //log response to logs TraceSwitch traceSwitch = new TraceSwitch("IPPTraceSwitch", "IPP Trace Switch"); this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, (int)traceSwitch.Level > (int)TraceLevel.Info ? "Got the response from service.\n Start Dump: \n" + resultString : "Got the response from service."); //if response is of not type pdf do as usual if (!isResponsePdf) { // If the response string is null then there was a communication mismatch with the server. So throw exception. if (string.IsNullOrWhiteSpace(resultString)) { exception = new IdsException(Resources.CommunicationErrorMessage, new CommunicationException(Resources.ResponseStreamNullOrEmptyMessage)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } else { if (this.context.ServiceType == IntuitServicesType.IPS) { // Handle errors here resultArguments = this.HandleErrors(resultString); } else { FaultHandler handler = new FaultHandler(this.context); IdsException idsException = handler.ParseErrorResponseAndPrepareException(resultString); if (idsException != null) { this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); resultArguments = new AsyncCallCompletedEventArgs(null, idsException); } else { resultArguments = new AsyncCallCompletedEventArgs(resultString, null); } } } } else //if response is of type pdf act accordingly { if (receiveBytes.Length <= 0) { //response equivalent to nullorwhitespace above so act in similar way exception = new IdsException(Resources.CommunicationErrorMessage, new CommunicationException(Resources.ResponseStreamNullOrEmptyMessage)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } //faults not applicable here since we are expecting only pdf in binary resultArguments = new AsyncCallCompletedEventArgs(null, null, receiveBytes); } return(resultArguments); }
internal WebResponse EndGetResponse(IAsyncResult asyncResult) { return(m_request.EndGetResponse(asyncResult)); }
private void UpdateResponse(IAsyncResult result) { try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); Stream resStream = response.GetResponseStream(); string tempString; int count; StringBuilder sb = new StringBuilder(); byte[] buf = new byte[0x2000]; do { count = resStream.Read(buf, 0, buf.Length); if (count != 0) { tempString = Encoding.ASCII.GetString(buf, 0, count); sb.Append(tempString); } }while (count > 0); string dataVer = Regex.Match(sb.ToString(), @"FoVChangerVer\[([0-9\.]*?)\]").Groups[1].Value; string dataSafe = Regex.Match(sb.ToString(), @"SafeToUse\[([A-Za-z]*?)\]").Groups[1].Value; string dataInfo = Regex.Unescape(HttpUtility.HtmlDecode(Regex.Match(sb.ToString(), @"UpdateInfo\[(.*?)\]").Groups[1].Value)); //MessageBox.Show(dataVer); if (!String.IsNullOrEmpty(dataSafe) && dataSafe.ToLower() == "vacdetected") { this.Invoke(new Action(() => { DialogResult vacResult = MessageBox.Show(this, "It has been reported that this FoV Changer may cause Valve Anti-Cheat to trigger a ban. " + "For any information, please check MapModNews.com.\n\n" + "Click 'OK' to exit the program, or 'Cancel' to continue using it AT YOUR OWN RISK.", "Detection alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); if (vacResult == DialogResult.OK) { Application.Exit(); } })); } //MessageBox.Show(dataVer); if (!String.IsNullOrEmpty(dataVer) && VersionNum(dataVer) > VersionNum(c_toolVer)) { this.Invoke(new Action(() => { if (updateChk) { MessageBox.Show(this, "Update v" + dataVer + " for the FoV Changer is available at MapModNews.com, or can be downloaded directly \nby clicking the \"Help\" button below." + (!String.IsNullOrEmpty(dataInfo) ? "\n\nAdditional infos:\n" + dataInfo : ""), "Update available", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, 0, "http://mw3fov.ftp.sh/"); } lblUpdateAvail.Text = " - Update v" + dataVer + " available"; lblUpdateAvail.Enabled = true; lblUpdateAvail.Visible = true; TimerBlink.Start(); })); } } catch {} requestSent = false; }
//trackingStatusList.TrackingList.Add(status); //foreach(XmlNode item in nodeElement.ChildNodes) //{ // DpdTrackingStatusViewModel status = new DpdTrackingStatusViewModel(); // if (item.Name == "description") status.Event = item.InnerText; // if (item.Name == "eventTime") status.EventDateTime = item.InnerText; // if (item.Name == "depotName") status.EventPlace = item.InnerText; // if (item.Name == "waybill") status.TrackingNumber = item.InnerText; // trackingStatusList.TrackingList.Add(status); //string s = item.Attributes["//description"].InnerText; //if (item.Name == "description") //{ // list.Add(item.InnerText); //} // } //List<string> list2 = new List<string>(); //list2 = list; //DpdTrackingStatusViewModel lastTrackingStatus; //if (xmlDoc.GetElementsByTagName("description").Item(0)==null) //{ // lastTrackingStatus = new DpdTrackingStatusViewModel() // { // Event = "brak", // EventDateTime = "brak", // EventPlace = "brak", // TrackingNumber = "brak" // }; //} //else //{ // lastTrackingStatus = new DpdTrackingStatusViewModel() // { // Event = xmlDoc.GetElementsByTagName("description").Item(0).InnerText, // EventDateTime = xmlDoc.GetElementsByTagName("eventTime").Item(0).InnerText, // EventPlace = xmlDoc.GetElementsByTagName("depotName").Item(0).InnerText, // TrackingNumber = xmlDoc.GetElementsByTagName("waybill").Item(0).InnerText // }; //} //return lastTrackingStatus; // sending soap request to webservice DPD private string SendSoap(string xmlRequest, string trackingNumber) { // get DPD config DpdConfigEntity dpdConfig = _myContex.DpdConfigs.First(); // SOAP url DPD string url = "https://dpdinfoservices.dpd.com.pl/DPDInfoServicesObjEventsService/DPDInfoServicesObjEvents"; XmlDocument soapXml = new XmlDocument(); soapXml.LoadXml(xmlRequest); // add config to XML soapXml.GetElementsByTagName("waybill").Item(0).InnerText = trackingNumber; soapXml.GetElementsByTagName("login").Item(0).InnerText = dpdConfig.Login; soapXml.GetElementsByTagName("password").Item(0).InnerText = dpdConfig.Password; soapXml.GetElementsByTagName("channel").Item(0).InnerText = dpdConfig.Channel; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.ContentType = "text/xml;charset=\"utf-8\""; webRequest.Accept = "text/xml"; webRequest.Method = "POST"; webRequest.Headers.Add("SOAPAction", "Vehicle"); using (Stream stream = webRequest.GetRequestStream()) { soapXml.Save(stream); } IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null); asyncResult.AsyncWaitHandle.WaitOne(); string soapResult; WebResponse webResponse = null; try { webResponse = webRequest.EndGetResponse(asyncResult); using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) { soapResult = rd.ReadToEnd(); } return(soapResult); } catch (Exception e) { if (e is WebException && ((WebException)e).Status == WebExceptionStatus.ProtocolError) { WebResponse errResp = ((WebException)e).Response; using (Stream respStream = errResp.GetResponseStream()) { StreamReader reader = new StreamReader(respStream); string text = reader.ReadToEnd(); return(text); } } } finally { webResponse.Close(); } return(""); }
private void OnGetResponse(IAsyncResult asyncResult) { byte[] imageBuffer = new byte[1024 * 1024]; // get the response HttpWebRequest req = (HttpWebRequest)asyncResult.AsyncState; try { HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(asyncResult); // find our magic boundary value string contentType = resp.Headers["Content-Type"]; if (!string.IsNullOrEmpty(contentType) && !contentType.Contains("=")) { throw new Exception("Invalid content-type header. The camera is likely not returning a proper MJPEG stream."); } string boundary = resp.Headers["Content-Type"].Split('=')[1].Replace("\"", ""); byte[] boundaryBytes = Encoding.UTF8.GetBytes(boundary.StartsWith("--") ? boundary : "--" + boundary); Stream s = resp.GetResponseStream(); BinaryReader br = new BinaryReader(s); _streamActive = true; byte[] buff = br.ReadBytes(ChunkSize); while (_streamActive) { // find the JPEG header int imageStart = buff.Find(JpegHeader); if (imageStart != -1) { // copy the start of the JPEG image to the imageBuffer int size = buff.Length - imageStart; Array.Copy(buff, imageStart, imageBuffer, 0, size); while (true) { buff = br.ReadBytes(ChunkSize); // find the boundary text int imageEnd = buff.Find(boundaryBytes); if (imageEnd != -1) { // copy the remainder of the JPEG to the imageBuffer Array.Copy(buff, 0, imageBuffer, size, imageEnd); size += imageEnd; byte[] frame = new byte[size]; Array.Copy(imageBuffer, 0, frame, 0, size); ProcessFrame(frame); // copy the leftover data to the start Array.Copy(buff, imageEnd, buff, 0, buff.Length - imageEnd); // fill the remainder of the buffer with new data and start over byte[] temp = br.ReadBytes(imageEnd); Array.Copy(temp, 0, buff, buff.Length - imageEnd, temp.Length); break; } // copy all of the data to the imageBuffer Array.Copy(buff, 0, imageBuffer, size, buff.Length); size += buff.Length; } } } #if WINRT resp.Dispose(); #else resp.Close(); #endif } catch (Exception ex) { #if WINRT if (Error != null) { _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Error(this, new ErrorEventArgs() { Message = ex.Message, ErrorCode = ex.HResult })); } #else if (Error != null) { _context?.Post(delegate { Error(this, new ErrorEventArgs() { Message = ex.Message }); }, null); } #endif return; } }
private void OnGetSessionRequestResponse(IAsyncResult result) { // grab the custom state object WebRequestState state = (WebRequestState)result.AsyncState; HttpWebRequest request = (HttpWebRequest)state.WebRequest; //state.TimeOutTimer.Dispose(); // get the Response HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(result); // The server must always return a 200 response code, // sending any session errors as specially-formatted identifiers. if (resp.StatusCode != HttpStatusCode.OK) { return; } Stream rs = resp.GetResponseStream(); int readlen; byte[] readbuf = new byte[1024]; MemoryStream ms = new MemoryStream(); while ((readlen = rs.Read(readbuf, 0, readbuf.Length)) > 0) { ms.Write(readbuf, 0, readlen); } byte[] recv = ms.ToArray(); if (recv.Length > 0) { string body = null; string stanzas = null; string res = Encoding.UTF8.GetString(recv, 0, recv.Length); ParseResponse(res, ref body, ref stanzas); Document doc = new Document(); doc.LoadXml(body); Body boshBody = doc.RootElement as Body; sid = boshBody.Sid; polling = boshBody.Polling; m_MaxPause = boshBody.MaxPause; byte[] bin = Encoding.UTF8.GetBytes(DummyStreamHeader + stanzas); base.FireOnReceive(bin, bin.Length); // cleanup webrequest resources ms.Close(); rs.Close(); resp.Close(); activeRequests--; if (activeRequests == 0) { StartWebRequest(); } } }
internal static void GetToken(SocialType type, ClientInfo client, string code, Action <AccessToken> action) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(GetTokenUrl(type, client, code)); httpWebRequest.Method = "POST"; httpWebRequest.BeginGetResponse((p) => { HttpWebRequest request = (HttpWebRequest)p.AsyncState; HttpWebResponse httpWebResponse; try { httpWebResponse = (HttpWebResponse)request.EndGetResponse(p); } catch (WebException ex) { Debug.WriteLine(ex.ToString()); return; } if (httpWebResponse != null) { using (var stream = httpWebResponse.GetResponseStream()) { AccessToken token = new AccessToken(); if (type == SocialType.Tencent) { using (var reader = new System.IO.StreamReader(stream)) { string text = reader.ReadToEnd(); if (!string.IsNullOrEmpty(text)) { //access_token=ec70e646177f025591e4282946c19b67&expires_in=604800&name=xshf12345 var acc = text.Split('&'); foreach (var item in acc) { var single = item.Split('='); if (single[0] == "access_token") { token.Token = single[1]; } else if (single[0] == "expires_in") { token.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToInt32(single[1])); } else if (single[0] == "name") { token.UserInfo = single[1]; } } token.OpenId = client.Tag; } } } else if (type == SocialType.Weibo) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Weibo.WeiboAccessToken)); var item = ser.ReadObject(stream) as Weibo.WeiboAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.uid; } else if (type == SocialType.Renren) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Renren.RenrenAccessToken)); var item = ser.ReadObject(stream) as Renren.RenrenAccessToken; item.ExpiresTime = DateTime.Now.AddSeconds(Convert.ToDouble(item.expires_in)); token.Token = item.access_token; token.ExpiresTime = item.ExpiresTime; token.UserInfo = item.user.name; } string filePath = string.Format(SocialAPI.ACCESS_TOKEN_PREFIX, type.ToString()); JsonHelper.SerializeData <AccessToken>(filePath, token); action(token); } } }, httpWebRequest); }
static void Main(string[] args) { try { // 這個網址服務將會提供將兩個整數相加起來,不過,可以指定要暫停幾秒鐘 string host = "https://lobworkshop.azurewebsites.net"; string path = "/api/RemoteSource/Add/15/43/5"; string url = $"{host}{path}"; // 使用 WebRequest.Create 工廠方法建立一個 HttpWebrequest 物件 HttpWebRequest myHttpWebRequest1 = (HttpWebRequest)WebRequest.Create(url); // 呼叫 BeginXXX 啟動非同步工作 Console.WriteLine($"啟動 APM 非同步方法 (Thread={Thread.CurrentThread.ManagedThreadId}):{DateTime.Now}"); IAsyncResult asyncResult = (IAsyncResult)myHttpWebRequest1.BeginGetResponse(null, null); for (int i = 0; i < 3; i++) { Console.WriteLine($" 處理其他事情 (Thread={Thread.CurrentThread.ManagedThreadId}):{DateTime.Now}"); Thread.Sleep(1000); } Console.WriteLine("come in YAYAYAYA"); // 開始進行輪詢非同步作業的狀態,看看是否已經完成 // 我們會使用 . 句號輸出,表示這個應用程式還在執行中,並沒有封鎖起來 // 在這個回圈內,會不斷地查看非同步工作是否已經完成,透過 IsCompleted 成員 // 這樣做法雖然不會造成 Thread Block,可以,可以看得出來,這樣做法會耗用大量的 CPU 資源 // 因為,我們需要不斷的察看非同步工作是否已經完成 while (asyncResult.IsCompleted != true) { // 我們會使用 . 句號輸出,表示這個應用程式還在執行中,並沒有封鎖起來 Console.WriteLine($" . (Thread={Thread.CurrentThread.ManagedThreadId}):{DateTime.Now}"); } // 若程式已經可以執行到這裡,那就表示非同步工作已經完成了 Console.WriteLine($"取得非同步方法結果 (Thread={Thread.CurrentThread.ManagedThreadId}):{DateTime.Now}"); WebResponse webResponse = myHttpWebRequest1.EndGetResponse(asyncResult); Console.WriteLine($"成功取得非同步方法結果 (Thread={Thread.CurrentThread.ManagedThreadId}):{DateTime.Now}"); Stream ReceiveStream = webResponse.GetResponseStream(); StreamReader reader = new StreamReader(ReceiveStream); string result = reader.ReadToEnd(); Console.WriteLine($"網頁執行結果:{result}"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } catch (WebException e) { Console.WriteLine("\nException raised!"); Console.WriteLine("\nMessage:{0}", e.Message); Console.WriteLine("\nStatus:{0}", e.Status); Console.WriteLine("Press any key to continue.........."); } catch (Exception e) { Console.WriteLine("\nException raised!"); Console.WriteLine("Source :{0} ", e.Source); Console.WriteLine("Message :{0} ", e.Message); Console.WriteLine("Press any key to continue.........."); Console.Read(); } }
private void endCashoutResponce(IAsyncResult AR) { try { CashOutData cd; HttpWebResponse httpResponce = (HttpWebResponse)_httpRequest.EndGetResponse(AR); using (StreamReader sr = new StreamReader(httpResponce.GetResponseStream())) { lastResponce = sr.ReadToEnd(); cd = Deserialize <CashOutData>(lastResponce); } httpResponce.Close(); if (cd == null || cd.status != "success") { throw new Exception(); } if (GameConfig.ShowGameBombs) { string[] bmbz = cd.mines.Split('-'); foreach (string s in bmbz) { int bS; if (int.TryParse(s, out bS)) { FadebombSquare(bS); } } } Log(cd.message); string url = string.Format("https://satoshimines.com/s/{0}/{1}/", cd.game_id, cd.random_string); Log("Url: {0}", url); AddWin(); bool ShouldStop = false; var data = BalanceStopShouldStop(out ShouldStop); if (GameConfig.StopAfterWin && running) { Log("Stop After win is enabled... Stopping..."); SaveLogDisk(); notFirstClear = false; running = false; } else if (ShouldStop && !running) { Log("Balance level met ({0} bits)... Stopping...", data.balance); SaveLogDisk(); notFirstClear = false; running = false; } CheckLastGame(); Log(""); int betSquare = getNextSquare(); PrepRequest("https://satoshimines.com/action/newgame.php"); byte[] newGameresponce = Bcodes("player_hash={0}&bet={1}&num_mines={2}" + postExtention, GameConfig.PlayerHash, GameConfig.BetCost.ToString("0.000000", new CultureInfo("en-US")), GameConfig.BombCount); if (running) { CheckWait(); getPostResponce(newGameresponce, EndNewGameResponce); } else { BSta(true); } } catch (Exception ex) { if (GameConfig.ShowExceptionWindow) { using (ExceptionForm except = new ExceptionForm(ex.ToString())) { except.ShowDialog(); } } Log("Failed to cashout."); BSta(true); } }
public static void AsyncResponseCallback(IAsyncResult ar) { RequestState requestState = ar.AsyncState as RequestState; HttpWebResponse httpWebResponse = null; try { HttpWebRequest httpWebRequest = requestState.httpWebRequest; httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(ar); //nofity get response requestState.request.onNotifyGetResponse(); requestState.httpWebResponse = httpWebResponse; //handle response headers HandleHttpWebResponseHeaders(requestState.response, httpWebResponse); Stream responseStream = httpWebResponse.GetResponseStream(); requestState.response.Body.StartHandleResponseBody(responseStream, delegate(bool isSuccess, Exception ex) { PrintResponseInfo(httpWebResponse); requestState.response.OnFinish(isSuccess, ex); requestState.Clear(); }); } catch (WebException webEx) { if (webEx.Response != null && webEx.Response is HttpWebResponse) { //nofity get response requestState.request.onNotifyGetResponse(); //handle response for [400, 500] httpWebResponse = (HttpWebResponse)webEx.Response; requestState.httpWebResponse = httpWebResponse; //handle response headers HandleHttpWebResponseHeaders(requestState.response, httpWebResponse); Stream responseStream = httpWebResponse.GetResponseStream(); requestState.response.Body.StartHandleResponseBody(responseStream, delegate(bool isSuccess, Exception ex) { PrintResponseInfo(httpWebResponse); requestState.response.OnFinish(isSuccess, ex); requestState.Clear(); }); } else { requestState.response.OnFinish(false, webEx); //abort requestState.Clear(); QLog.Error(TAG, webEx.Message, webEx); } } catch (Exception ex) { requestState.response.OnFinish(false, ex); //abort requestState.Clear(); QLog.Error(TAG, ex.Message, ex); } }
/// <summary> /// GET GOMOSTEAM SITE MIRRORS /// </summary> /// <param name="url"></param> /// <param name="_tempThred"></param> /// <param name="episode"></param> void DownloadGomoSteam(string url, TempThread tempThred, int episode) { bool done = true; print("EXTRACTING GOMO: " + url); try { try { string d = ""; if (d == "") { try { // d = DownloadString(url, tempThred, false, 2); if (!GetThredActive(tempThred)) { return; }; // COPY UPDATE PROGRESS TODO CHECK d = DownloadString(url, tempThred, 2); if (!GetThredActive(tempThred)) { return; } ; // COPY UPDATE PROGRESS } catch (System.Exception) { print("Error gogo"); } } if (d == "") { print("GetHTML SAVE"); d = GetHTML(url); if (!GetThredActive(tempThred)) { return; } ; } if (d == "") { d = HTMLGet(url, "https://" + GOMOURL); if (d != "") { print("HTMLGET SAVE"); } if (!GetThredActive(tempThred)) { return; } ; } if (d != "") // If not failed to connect { debug("Passed gogo download site"); // ----- JS EMULATION, CHECK USED BY WEBSITE TO STOP WEB SCRAPE BOTS, DID NOT STOP ME >:) ----- string tokenCode = FindHTML(d, "var tc = \'", "'"); string _token = FindHTML(d, "_token\": \"", "\""); string funct = "function _tsd_tsd_ds(" + FindHTML(d, "function _tsd_tsd_ds(", "</script>").Replace("\"", "'") + " log(_tsd_tsd_ds('" + tokenCode + "'))"; // print(funct); if (funct == "function _tsd_tsd_ds( log(_tsd_tsd_ds(''))") { debug(d); // ERROR IN LOADING JS } string realXToken = ""; var engine = new Engine() .SetValue("log", new Action <string>((a) => { realXToken = a; })); engine.Execute(@funct); if (!GetThredActive(tempThred)) { return; } ; // COPY UPDATE PROGRESS //GetAPI(realXToken, tokenCode, _token, tempThred, episode); print("PAssed js test" + realXToken); System.Uri myUri = new System.Uri("https://" + GOMOURL + "/decoding_v3.php"); // Can't DownloadString because of RequestHeaders (Anti-bot) HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(myUri); // --- Headers --- webRequest.Method = "POST"; webRequest.Headers.Add("x-token", realXToken); webRequest.Headers.Add("X-Requested-With", "XMLHttpRequest"); webRequest.Headers.Add("DNT", "1"); webRequest.Headers.Add("Cache-Control", "max-age=0, no-cache"); webRequest.Headers.Add("TE", "Trailers"); webRequest.Headers.Add("Pragma", "Trailers"); webRequest.ContentType = "application/x-www-form-urlencoded"; done = false; print("Passed token"); webRequest.BeginGetRequestStream(new AsyncCallback((IAsyncResult callbackResult) => { HttpWebRequest _webRequest = (HttpWebRequest)callbackResult.AsyncState; Stream postStream = _webRequest.EndGetRequestStream(callbackResult); string requestBody = true ? ("tokenCode=" + tokenCode + "&_token=" + _token) : "type=epis&xny=hnk&id=" + tokenCode; // --- RequestHeaders --- byte[] byteArray = Encoding.UTF8.GetBytes(requestBody); postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); print("PASSED TOKENPOST"); if (!GetThredActive(tempThred)) { return; } ; // BEGIN RESPONSE try { _webRequest.BeginGetResponse(new AsyncCallback((IAsyncResult _callbackResult) => { HttpWebRequest request = (HttpWebRequest)_callbackResult.AsyncState; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(_callbackResult); try { using StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()); if (!GetThredActive(tempThred)) { print(":("); return; } ; print("GOT RESPONSE:"); string result = httpWebStreamReader.ReadToEnd(); print("RESULT:::" + result); try { if (result != "") { // --------------- GOT RESULT!!!!! --------------- // --------------- MIRROR LINKS --------------- string veryURL = FindHTML(result, "https:\\/\\/verystream.com\\/e\\/", "\""); string gunURL = "https://gounlimited.to/" + FindHTML(result, "https:\\/\\/gounlimited.to\\/", ".html") + ".html"; string onlyURL = "https://onlystream.tv" + FindHTML(result, "https:\\/\\/onlystream.tv", "\"").Replace("\\", ""); //string gogoStream = FindHTML(result, "https:\\/\\/" + GOMOURL, "\""); string upstream = FindHTML(result, "https:\\/\\/upstream.to\\/embed-", "\""); string mightyupload = FindHTML(result, "https:\\/\\/mightyupload.com\\/embed-", "\""); //FindHTML(result, "http:\\/\\/mightyupload.com\\/", "\"").Replace("\\/", "/"); //["https:\/\/upstream.to\/embed-05mzggpp3ohg.html","https:\/\/gomo.to\/vid\/eyJ0eXBlIjoidHYiLCJzIjoiMDEiLCJlIjoiMDEiLCJpbWQiOiJ0dDA5NDQ5NDciLCJfIjoiMzQyMDk0MzQzMzE4NTEzNzY0IiwidG9rZW4iOiI2NjQ0MzkifQ,,&noneemb","https:\/\/hqq.tv\/player\/embed_player.php?vid=SGVsWVI5aUNlVTZxTTdTV09RY0x6UT09&autoplay=no",""] if (upstream != "") { string _d = DownloadString("https://upstream.to/embed-" + upstream); if (!GetThredActive(tempThred)) { return; } ; const string lookFor = "file:\""; int prio = 16; while (_d.Contains(lookFor)) { prio--; string ur = FindHTML(_d, lookFor, "\""); _d = RemoveOne(_d, lookFor); string label = FindHTML(_d, "label:\"", "\""); AddPotentialLink(episode, ur, "HD Upstream", prio, label); } } /* * if (mightyupload != "") { * print("MIGHT: " + mightyupload); * string baseUri = "http://mightyupload.com/embed-" + mightyupload; * //string _d = DownloadString("http://mightyupload.com/" + mightyupload); * string post = "op=download1&usr_login=&id=" + (mightyupload.Replace(".html", "")) + "&fname=" + (mightyupload.Replace(".html", "") + "_play.mp4") + "&referer=&method_free=Free+Download+%3E%3E"; * * string _d = PostRequest(baseUri, baseUri, post, tempThred);//op=download1&usr_login=&id=k9on84m2bvr9&fname=tt0371746_play.mp4&referer=&method_free=Free+Download+%3E%3E * print("RESMIGHT:" + _d); * if (!GetThredActive(tempThred)) { return; }; * string ur = FindHTML(_d, "<source src=\"", "\""); * AddPotentialLink(episode, ur, "HD MightyUpload", 16); * }*/ /* * if (gogoStream.EndsWith(",&noneemb")) { * result = RemoveOne(result, ",&noneemb"); * gogoStream = FindHTML(result, "https:\\/\\/" + GOMOURL, "\""); * } * * * gogoStream = gogoStream.Replace(",,&noneemb", "").Replace("\\", ""); * */ /* * Episode ep = activeMovie.episodes[episode]; * if (ep.links == null) { * activeMovie.episodes[episode] = new Episode() { links = new List<Link>(), date = ep.date, description = ep.description, name = ep.name, posterUrl = ep.posterUrl, rating = ep.rating, id = ep.id }; * }*/ if (veryURL != "") { try { if (!GetThredActive(tempThred)) { return; } ; d = DownloadString("https://verystream.com/e/" + veryURL); if (!GetThredActive(tempThred)) { return; } ; // print(d); debug("-------------------- HD --------------------"); url = "https://verystream.com/gettoken/" + FindHTML(d, "videolink\">", "<"); debug(url); if (url != "https://verystream.com/gettoken/") { /* * if (!LinkListContainsString(activeMovie.episodes[episode].links, url)) { * // print(activeMovie.episodes[episode].Progress); * activeMovie.episodes[episode].links.Add(new Link() { url = url, priority = 10, name = "HD Verystream" }); * linkAdded?.Invoke(null, 1); * }*/ AddPotentialLink(episode, url, "HD Verystream", 20); } debug("--------------------------------------------"); debug(""); } catch (System.Exception) { } } else { debug("HD Verystream Link error (Read api)"); debug(""); } // activeMovie.episodes[episode] = SetEpisodeProgress(activeMovie.episodes[episode]); const string __lookFor = "https:\\/\\/gomo.to\\/vid\\/"; while (result.Contains(__lookFor)) { string gogoStream = FindHTML(result, __lookFor, "\""); result = RemoveOne(result, __lookFor); if (gogoStream != "") { debug(gogoStream); try { if (!GetThredActive(tempThred)) { return; } ; string trueUrl = "https://" + GOMOURL + "/vid/" + gogoStream; print(trueUrl); d = DownloadString(trueUrl); print("-->><<__" + d); if (!GetThredActive(tempThred)) { return; } ; //print(d); // print("https://gomostream.com" + gogoStream); //https://v16.viduplayer.com/vxokfmpswoalavf4eqnivlo2355co6iwwgaawrhe7je3fble4vtvcgek2jha/v.mp4 debug("-------------------- HD --------------------"); url = GetViduplayerUrl(d); debug(url); if (!url.EndsWith(".viduplayer.com/urlset/v.mp4") && !url.EndsWith(".viduplayer.com/vplayer/v.mp4") && !url.EndsWith(".viduplayer.com/adb/v.mp4")) { /*if (!LinkListContainsString(activeMovie.episodes[episode].links, url)) { * //print(activeMovie.episodes[episode].Progress); * activeMovie.episodes[episode].links.Add(new Link() { url = url, priority = 9, name = "HD Viduplayer" }); * linkAdded?.Invoke(null, 1); * * }*/ debug("ADDED"); AddPotentialLink(episode, url, "HD Viduplayer", 19); } debug("--------------------------------------------"); debug(""); } catch (System.Exception) { } } else { debug("HD Viduplayer Link error (Read api)"); debug(""); } } // activeMovie.episodes[episode] = SetEpisodeProgress(activeMovie.episodes[episode]); if (gunURL != "https://gounlimited.to/.html" && gunURL != "" && gunURL != "https://gounlimited.to/") { try { if (!GetThredActive(tempThred)) { return; } ; d = DownloadString(gunURL); if (!GetThredActive(tempThred)) { return; } ; string mid = FindHTML(d, "mp4|", "|"); string server = FindHTML(d, mid + "|", "|"); url = "https://" + server + ".gounlimited.to/" + mid + "/v.mp4"; if (mid != "" && server != "") { /* * if (!LinkListContainsString(activeMovie.episodes[episode].links, url)) { * // print(activeMovie.episodes[episode].Progress); * * activeMovie.episodes[episode].links.Add(new Link() { url = url, priority = 8, name = "HD Go Unlimited" }); * linkAdded?.Invoke(null, 1); * * }*/ AddPotentialLink(episode, url, "HD Go Unlimited", 18); } debug("-------------------- HD --------------------"); debug(url); debug("--------------------------------------------"); debug(""); } catch (System.Exception) { } } else { debug("HD Go Link error (Read api)"); debug(""); } // activeMovie.episodes[episode] = SetEpisodeProgress(activeMovie.episodes[episode]); if (onlyURL != "" && onlyURL != "https://onlystream.tv") { try { if (!GetThredActive(tempThred)) { return; } ; d = DownloadString(onlyURL); if (!GetThredActive(tempThred)) { return; } ; string _url = FindHTML(d, "file:\"", "\""); if (_url == "") { _url = FindHTML(d, "src: \"", "\""); } bool valid = false; if (CheckIfURLIsValid(_url)) // NEW USES JW PLAYER I THNIK, EASIER LINK EXTRACTION { url = _url; valid = true; } else // OLD SYSTEM I THINK { string server = ""; //FindHTML(d, "urlset|", "|"); string mid = FindHTML(d, "logo|", "|"); if (mid == "" || mid.Length < 10) { mid = FindHTML(d, "mp4|", "|"); } string prefix = FindHTML(d, "ostreamcdn|", "|"); url = ""; if (server != "") { url = "https://" + prefix + ".ostreamcdn.com/" + server + "/" + mid + "/v/mp4"; // /index-v1-a1.m3u8 also works if you want the m3u8 file instead } else { url = "https://" + prefix + ".ostreamcdn.com/" + mid + "/v/mp4"; } if (mid != "" && prefix != "" && mid.Length > 10) { valid = true; } } if (valid) { AddPotentialLink(episode, url, "HD Onlystream", 17); } else { debug(d); debug("FAILED URL: " + url); } debug("-------------------- HD --------------------"); debug(url); debug("--------------------------------------------"); debug(""); } catch (System.Exception) { } } else { debug("HD Only Link error (Read api)"); debug(""); } done = true; } else { done = true; debug("DA FAILED"); } } catch (Exception) { done = true; } } catch (Exception _ex) { error("FATAL EX IN TOKENPOST2:" + _ex); } } catch (Exception _ex) { error("FATAL EX IN TOKENPOST2:" + _ex); } }), _webRequest); } catch (Exception _ex) { error("FATAL EX IN TOKENPOST:" + _ex); } }), webRequest); } else { debug("Dident get gogo"); } } catch (System.Exception) { debug("Error"); } } finally { while (!done) { Thread.Sleep(20); } } }
private void OnGetResponse(IAsyncResult asyncResult) { // get the response HttpWebRequest req = (HttpWebRequest)asyncResult.AsyncState; try { HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(asyncResult); Stream s = resp.GetResponseStream(); while (true) { CommonHeader heder = new CommonHeader(); //ByteArrayToStructure(s, ref heder); var buff = ReadBytes(s, 8); heder.StartByte = buff[0]; heder.Type = buff[1]; heder.SequenceNo = BitConverter.ToInt16(buff, 2);; heder.TimeStamp = BitConverter.ToInt32(buff, 4);; PayloadHeader playload = new PayloadHeader(); //ByteArrayToStructure(s, ref playload); buff = ReadBytes(s, 128); playload.StartCode = BitConverter.ToInt32(buff, 0); playload.JpgDataSize = BitConverter.ToUInt16(new byte[] { buff[6], buff[5], buff[4], 0 }, 0); playload.PadingSize = buff[7]; if (((CommonHeader)heder).Type == 0x02) { if (playload.JpgDataSize > 0) { var data = ReadBytes(s, playload.JpgDataSize); _liveViewData.FocusX = BitConverter.ToInt16(new byte[] { data[1], data[0] }, 0); _liveViewData.FocusY = BitConverter.ToInt16(new byte[] { data[3], data[2] }, 0);; _liveViewData.FocusFrameXSize = BitConverter.ToInt16(new byte[] { data[5], data[4] }, 0) - _liveViewData.FocusX; _liveViewData.FocusFrameYSize = BitConverter.ToInt16(new byte[] { data[7], data[6] }, 0) - _liveViewData.FocusY; _liveViewData.HaveFocusData = true; _liveViewData.Focused = data[9] != 0; _liveViewData.ImageWidth = 10000; _liveViewData.ImageHeight = 10000; _liveViewData.IsLiveViewRunning = true; Console.WriteLine(playload.JpgDataSize); } } else { _liveViewData.ImageData = ReadBytes(s, playload.JpgDataSize); } if (playload.PadingSize > 0) { ReadBytes(s, playload.PadingSize); } if (_shoulStopLiveView) { break; } } resp.Close(); } catch (Exception ex) { Log.Error("Unable to download stream ", ex); } }
public static void readHttpRequest(Uri location, Stream data, out String mimeType, CancellationToken token, Action <long, long> progressCallback = null) { HttpWebResponse response = null; Stream responseStream = null; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(location); request.Method = "GET"; request.Timeout = HTTP_TIMEOUT_MS; IAsyncResult requestResult = request.BeginGetResponse(null, null); while (!requestResult.IsCompleted) { if (token.IsCancellationRequested) { request.Abort(); throw new OperationCanceledException(token); } Thread.Sleep(100); } response = (HttpWebResponse)request.EndGetResponse(requestResult); mimeType = response.ContentType; responseStream = response.GetResponseStream(); responseStream.ReadTimeout = HTTP_TIMEOUT_MS; int bufSize = HTTP_READ_BUFFER_SIZE_BYTES; int count = 0; byte[] buffer = new byte[bufSize]; long total = 0; while ((count = responseStream.Read(buffer, 0, bufSize)) > 0) { if (token.IsCancellationRequested) { throw new OperationCanceledException(token); } data.Write(buffer, 0, count); if (progressCallback != null) { total += count; progressCallback(total, response.ContentLength); } } data.Seek(0, System.IO.SeekOrigin.Begin); } finally { if (responseStream != null) { responseStream.Close(); } if (response != null) { response.Close(); } } }
public void RequsetAsync <T>(RequsetMethod method, string url, object data, List <HttpHeader> headers, bool noToken, Action <T> onResponse) where T : class, new() { Encoding encoding = Encoding.UTF8; if (url.ToLower().Contains("https://") || url.Contains("http://")) { } else { url = BaseUrl + url; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl + url); // 如果直接精确到地址不用加服务器基础地址 if (url.ToLower().Contains("https://") || url.Contains("http://")) { request = (HttpWebRequest)WebRequest.Create(url); } request.Method = method.ToString(); // 添加token if (!noToken) { request.Headers.Add("Authorization", "Bearer " + Token.AccessToken); } // 添加自定义头 if (headers != null && headers.Count > 0) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } // 统一这一种格式数据 request.ContentType = "application/json;charset=utf-8"; request.BeginGetRequestStream(new AsyncCallback((result) => { HttpWebRequest req = (HttpWebRequest)result.AsyncState; // 有数据正文,发送数据正文 if (data != null) { var jsonData = Common.SerializeJSON(data); Stream postStream = req.EndGetRequestStream(result); byte[] requsetData; requsetData = Encoding.UTF8.GetBytes(jsonData); postStream.Write(requsetData, 0, requsetData.Length); postStream.Close(); } req.BeginGetResponse(new AsyncCallback(responseResult => { HttpWebRequest req1 = (HttpWebRequest)responseResult.AsyncState; if (responseResult.IsCompleted) { var webResponse = req1.EndGetResponse(responseResult); using (var stream = webResponse.GetResponseStream()) { using (var read = new StreamReader(stream)) { if (onResponse != null) { onResponse.Invoke(Common.DeserializeJSON <T>(read.ReadToEnd())); } } } } }), req); }), request); }
/// <summary> /// /// </summary> /// <param name="asynchronousResult"></param> private void downloadCallback(IAsyncResult asynchronousResult) { DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState; HttpWebRequest request = reqState.request; string callbackId = reqState.options.CallbackId; try { HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); // send a progress change event DispatchFileTransferProgress(0, response.ContentLength, callbackId); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create any directories in the path that do not exist string directoryName = getDirectoryName(reqState.options.FilePath); if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName)) { isoFile.CreateDirectory(directoryName); } // create the file if not exists if (!isoFile.FileExists(reqState.options.FilePath)) { var file = isoFile.CreateFile(reqState.options.FilePath); file.Close(); } using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile)) { long totalBytes = response.ContentLength; int bytesRead = 0; using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { int BUFFER_SIZE = 1024; byte[] buffer; while (true) { buffer = reader.ReadBytes(BUFFER_SIZE); // fire a progress event ? bytesRead += buffer.Length; if (buffer.Length > 0 && !reqState.isCancelled) { writer.Write(buffer); DispatchFileTransferProgress(bytesRead, totalBytes, callbackId); } else { writer.Close(); reader.Close(); fileStream.Close(); break; } System.Threading.Thread.Sleep(1); } } } } if (reqState.isCancelled) { isoFile.DeleteFile(reqState.options.FilePath); } } if (reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)), callbackId); } else { File.FileEntry entry = new File.FileEntry(reqState.options.FilePath); DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId); } } catch (IsolatedStorageException) { // Trying to write the file somewhere within the IsoStorage. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (SecurityException) { // Trying to write the file somewhere not allowed. DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } catch (WebException webex) { // TODO: probably need better work here to properly respond with all http status codes back to JS // Right now am jumping through hoops just to detect 404. HttpWebResponse response = (HttpWebResponse)webex.Response; if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound) || webex.Status == WebExceptionStatus.UnknownError) { // Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!! // "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away." // FACEPALM // Or just cast it to an int, whiner ... -jm int statusCode = (int)response.StatusCode; string body = ""; using (Stream streamResponse = response.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(streamResponse)) { body = streamReader.ReadToEnd(); } } FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body); DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), callbackId); } else { lock (reqState) { if (!reqState.isCancelled) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId); } else { Debug.WriteLine("It happened"); } } } } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)), callbackId); } //System.Threading.Thread.Sleep(1000); if (InProcDownloads.ContainsKey(reqState.options.Id)) { InProcDownloads.Remove(reqState.options.Id); } }