static IObservable <TResult> AbortableDeferredAsyncRequest <TResult>(Func <AsyncCallback, object, IAsyncResult> begin, Func <IAsyncResult, TResult> end, System.Net.WebRequest request) { var result = Observable.Create <TResult>(observer => { var isCompleted = -1; var subscription = Observable.FromAsyncPattern <TResult>(begin, ar => { try { Interlocked.Increment(ref isCompleted); return(end(ar)); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.RequestCanceled) { return(default(TResult)); } throw; } })() .Subscribe(observer); return(Disposable.Create(() => { if (Interlocked.Increment(ref isCompleted) == 0) { subscription.Dispose(); request.Abort(); } })); }); return(result); }
public long GetDownloadSizeOfBundles(List <AssetLoader.AssetBundleHash> assetBundlesToDownload) { int size = 0; for (int i = 0; i < assetBundlesToDownload.Count; i++) { #if UNITY_ANDROID System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "Android/" + assetBundlesToDownload[i].assetBundle); #endif #if UNITY_IOS System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "iOS/" + assetBundlesToDownload[i].assetBundle); #endif req.Method = "HEAD"; req.Timeout = 10000; int ContentLength; using (System.Net.WebResponse resp = req.GetResponse()) { if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength)) { size += ContentLength; //Debug.Log(assetBundlesToDownload[i].assetBundle + ", size: " + ContentLength); } resp.Close(); } req.Abort(); req = null; //System.GC.Collect(); } return(size); }
private string HttpPost(string url, byte[] data, IDictionary <object, string> headers = null) { string str = ""; System.Net.WebRequest request = HttpWebRequest.Create(url); request.Method = "POST"; if (data != null) { request.ContentLength = data.Length; } request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; if (headers != null) { foreach (var v in headers) { if (v.Key is HttpRequestHeader) { request.Headers[(HttpRequestHeader)v.Key] = v.Value; } else { request.Headers[v.Key.ToString()] = v.Value; } } } Stream writer = request.GetRequestStream(); writer.Write(data, 0, data.Length); writer.Close(); HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); str = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(response.StatusDescription); } finally { if (request != null) { request.Abort(); } } return(str); }
void sendThread() { log.addLog("http_get: Send Thread started"); Uri URI = new Uri("http://" + _sHost + "/homewatch/power/index.php" + "?"); System.Net.WebRequest req = null; System.Net.WebResponse resp = null; ec3k_data ec3k; try { while (bRunThread) { ec3k = new ec3k_data(""); try { lock (lockQueue) { if (sendQueue.Count > 0) { ec3k = sendQueue.Dequeue(); } //queue count>0 } //lock if (ec3k._bValid) { string sGet = ec3k.getPostString(); //make the request log.addLog("http_get: WEB GET=" + URI + sGet); req = System.Net.WebRequest.Create(URI + sGet); //req.Proxy = new System.Net.WebProxy(ProxyString, true); //true means no proxy req.Timeout = 5000; resp = req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); log.addLog("http_get: RESP=" + sr.ReadToEnd().Trim()); }//bValid Thread.Sleep(1000); } catch (WebException ex) { log.addLog("http_get: WebException in sendThread(): " + ex.Message); } catch (Exception ex) { log.addLog("http_get: web get exception: " + ex.Message); } } ; } catch (Exception ex) { log.addLog("http_get: Exception in sendThread(): " + ex.Message); } try{ resp.Close(); }catch (Exception) {} try{ req.Abort(); }catch (Exception) {} log.addLog("http_get: Send Thread ended"); }
private void BeginRequest(WebRequest request, AsyncCallback callback, object state) { var result = request.BeginGetResponse(callback, state); ClientEngine.MainLoop.QueueTimeout(RequestTimeout, delegate { if (!result.IsCompleted) request.Abort(); return false; }); }
//float lastCheckTime = 0f; public IEnumerator GetDownloadSizeOfBundlesA(List <AssetLoader.AssetBundleHash> assetBundlesToDownload, System.Action <long> result) { int size = 0; int count = assetBundlesToDownload.Count; //SceneLogIn.Instance.labelCheckAsset.text = "Calculate download size"; for (int i = 0; i < count; i++) { #if UNITY_ANDROID System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "Android/" + assetBundlesToDownload[i].assetBundle); #endif #if UNITY_IOS System.Net.WebRequest req = System.Net.HttpWebRequest.Create(url + "iOS/" + assetBundlesToDownload[i].assetBundle); #endif req.Method = "HEAD"; req.Timeout = 10000; int ContentLength; using (System.Net.WebResponse resp = req.GetResponse()) { if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength)) { size += ContentLength; //Debug.Log(assetBundlesToDownload[i].assetBundle + ", size: " + ContentLength); } resp.Close(); } req.Abort(); req = null; //System.GC.Collect(); //SceneLogIn.Instance.labelCheckAsset.text = "Calculate download size"; //if (Time.time > lastCheckTime + 1f) //{ // SceneLogIn.Instance.labelCheckAsset.text = "Calculate download size (" + i + "/" + count + ")"; // SceneLogIn.Instance.labelCheckAsset.Update(); // lastCheckTime = Time.time; // yield return new WaitForSeconds(0.1f); //} } result(size); //return size; yield break; }
private static void AbortRequest(WebRequest request) { try { if (request != null) { request.Abort(); } } catch (Exception exception) { if (((exception is OutOfMemoryException) || (exception is StackOverflowException)) || (exception is ThreadAbortException)) { throw; } } }
void Image_Change() { try { string[] a = null; string[] b = null; int suiji = intSuijishu(1, 6); Task.Run(() => { WebClient webClient = new WebClient(); a = Encoding.UTF8.GetString(webClient.DownloadData("http://106.14.64.250/api/" + suiji + ".html")).Split('#'); webClient.Dispose(); b = a[1].Split('|'); System.Net.WebRequest webreq = System.Net.WebRequest.Create("http://106.14.64.250/api/" + b[1]); System.Net.WebResponse webres = webreq.GetResponse(); System.IO.Stream stream = webres.GetResponseStream(); System.Drawing.Image img1 = System.Drawing.Image.FromStream(stream); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img1); IntPtr hBitmap = bmp.GetHbitmap(); this.Dispatcher.BeginInvoke(new Action(() => { ImageLabel1.Content = a[0]; ImageLabel.Text = b[0]; Image.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); })); stream.Dispose(); webreq.Abort(); webres.Dispose(); img1.Dispose(); bmp.Dispose(); GC.Collect(); this.Dispatcher.BeginInvoke(new Action(() => { Image_Loading.Visibility = Visibility.Collapsed; })); }); } catch { Image_Loading.Visibility = Visibility.Collapsed; } }
public override void Abort() { _internalWebRequest.Abort(); }
public Response(WebRequest request) { int retries = 0; const int maxRetries = 3; WebException lastEx = null; do { try { if (this.response != null) { try { this.response.Close(); } catch { } } request.Timeout = 30000; this.response = request.GetResponse(); lastEx = null; } catch (WebException ex) { Debug.WriteLine("Response(request) failed with " + ex.Message); long contentLength = request.ContentLength; try { this.response.Close(); } catch { } try { request.Abort(); } catch { } lastEx = ex; retries += 1; int? statusCode; HttpWebResponse response = ex.Response as HttpWebResponse; if (response == null) { statusCode = null; if (AWSAuthConnection.verbose) Console.WriteLine("WebException ({0}) but couldn't determine status code", ex.Message); } else { statusCode = (int)response.StatusCode; if (AWSAuthConnection.verbose) Console.WriteLine("WebException ({0}) with status code {1}", ex.Message, statusCode); } if (contentLength == -1 && (statusCode == null || (statusCode >= 500 && statusCode < 600))) { if (AWSAuthConnection.verbose) Console.Error.WriteLine("Rebuilding request automatically"); // we can rebuild the request here and retry it (sadly there's no request.Reset()) WebRequest newRequest = WebRequest.Create(request.RequestUri); foreach (string key in request.Headers.AllKeys) if (key != "Host" && key != "Connection") // can't set either of these directly newRequest.Headers.Add(key, request.Headers[key]); newRequest.Method = request.Method; if (newRequest is HttpWebRequest) { HttpWebRequest httpReq = newRequest as HttpWebRequest; httpReq.AllowWriteStreamBuffering = false; } request = newRequest; System.Threading.Thread.Sleep(250 * (int)Math.Pow(2, retries - 1)); } else { request = null; throw; } } } while (retries < maxRetries && lastEx != null); if (lastEx != null) { Debug.WriteLine("lastEx not null"); string msg = lastEx.Response != null ? Utils.slurpInputStream(lastEx.Response.GetResponseStream()) : lastEx.Message; try { lastEx.Response.Close(); } catch { // ignore } throw new WebException(msg, lastEx, lastEx.Status, lastEx.Response); } }
/// 访问URL地址 public string CallWebPage(string url, int httpTimeout, Encoding postEncoding) { string rStr = ""; System.Net.WebRequest req = null; System.Net.WebResponse resp = null; System.IO.Stream os = null; System.IO.StreamReader sr = null; try { //创建连接 req = System.Net.WebRequest.Create(url); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "GET"; //时间 if (httpTimeout > 0) { req.Timeout = httpTimeout; } //读取返回结果 resp = req.GetResponse(); sr = new System.IO.StreamReader(resp.GetResponseStream(), postEncoding); rStr = sr.ReadToEnd(); } catch (Exception ex) { throw (ex); } finally { try { //关闭资源 if (os != null) { os.Dispose(); os.Close(); } if (sr != null) { sr.Dispose(); sr.Close(); } if (resp != null) { resp.Close(); } if (req != null) { req.Abort(); req = null; } } catch (Exception ex2) { throw (ex2); } } return(rStr); }
static IEnumerable<Task> _getResponseAsync(TaskCompletionSource<WebResponse> tcs, WebRequest request, TimeSpan timeout) { using (var cancellation_token = new Concurrency.TimeoutToken(timeout)) using (var registration_token = cancellation_token.Token.Register(() => { request.Abort(); })) { using (var task_get_response = request.GetResponseAsync()) { yield return task_get_response; tcs.SetFromTask(task_get_response); yield break; } } }
public void Start() { if (StreamState == StreamState.Stop && !_isNew) { return; } this.Raise(StreamStarted); SetStreamState(StreamState.Resume); _currentWebRequest = _generateWebRequest(); _currentStreamReader = CreateStreamReaderFromWebRequest(_currentWebRequest); int numberOfRepeatedFailures = 0; while (StreamState != StreamState.Stop) { if (StreamState == StreamState.Pause) { using (EventWaitHandle tmpEvent = new ManualResetEvent(false)) { tmpEvent.WaitOne(TimeSpan.FromSeconds(STREAM_RESUME_DELAY)); } continue; } try { var jsonResponse = GetJsonResponseFromReader(); var isJsonResponseValid = jsonResponse != null; if (!isJsonResponseValid) { if (TryHandleInvalidResponse(numberOfRepeatedFailures)) { ++numberOfRepeatedFailures; continue; } break; } numberOfRepeatedFailures = 0; if (jsonResponse == string.Empty) { continue; } if (StreamState == StreamState.Resume && !_processObject(jsonResponse)) { SetStreamState(StreamState.Stop); break; } } catch (Exception ex) { if (!ShouldContinueAfterHandlingException(ex)) { SetStreamState(StreamState.Stop); break; } } } if (_currentWebRequest != null) { _currentWebRequest.Abort(); } if (_currentStreamReader != null) { _currentStreamReader.Dispose(); } }
private StreamReader CreateStreamReaderFromWebRequest(WebRequest webRequest) { if (webRequest == null) { SetStreamState(StreamState.Stop); return null; } StreamReader reader = null; try { var twitterQuery = _twitterQueryFactory.Create(webRequest.RequestUri.AbsoluteUri); var queryBeforeExecuteEventArgs = new QueryBeforeExecuteEventArgs(twitterQuery); _tweetinviEvents.RaiseBeforeQueryExecute(queryBeforeExecuteEventArgs); if (queryBeforeExecuteEventArgs.Cancel) { SetStreamState(StreamState.Stop); return null; } // TODO : LINVI - THIS CODE HAS CHANGED AND NEEDS TO BE CHECKED WITH ASP.NET var responseStream = _webHelper.GetResponseStreamAsync(webRequest).Result; if (responseStream != null) { reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); } } catch (WebException wex) { HandleWebException(wex); } catch (Exception ex) { if (ex is ArgumentException) { if (ex.Message == "Stream was not readable.") { webRequest.Abort(); } } _lastException = ex; SetStreamState(StreamState.Stop); } return reader; }
private bool CheckCancel(BackgroundWorker worker, DoWorkEventArgs e, WebRequest request) { if (worker.CancellationPending) { request.Abort(); e.Cancel = true; return true; } return false; }
private void EndStreaming(WebRequest request) { _isStreaming = false; var stream = new MemoryStream(_endStreamBytes); var args = new WebQueryResponseEventArgs(stream); OnQueryResponse(args); request.Abort(); }
protected void CreateHtml(object sender, EventArgs e) { try { //文件存放根目录 string RootFilePath = "/Html/Ranking/"; //域名 string domain = Request.Url.OriginalString.ToLower().Replace("/admin/sconfig/createranking.aspx", ""); //System.Configuration.ConfigurationSettings.AppSettings["Domain"].TrimEnd( '/' ); //Ranking.aspx System.Net.WebRequest rq = System.Net.WebRequest.Create(domain + "/Ranking2.aspx"); System.Net.HttpWebResponse rp = (System.Net.HttpWebResponse)rq.GetResponse(); System.IO.Stream pageStream = rp.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(pageStream)) { //读取 string tmp = sr.ReadToEnd(); //无参数的Ranking.html string path = HttpContext.Current.Server.MapPath(RootFilePath + "Ranking.html"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8)) { sw.Write(tmp); } } rq.Abort(); rp.Close(); pageStream.Close(); //RankFascination.aspx rq = System.Net.WebRequest.Create(domain + "/RankFascination2.aspx"); rp = (System.Net.HttpWebResponse)rq.GetResponse(); pageStream = rp.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(pageStream)) { //读取 string tmp = sr.ReadToEnd(); //无参数的Ranking.html string path = HttpContext.Current.Server.MapPath(RootFilePath + "RankFascination.html"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8)) { sw.Write(tmp); } } rq.Abort(); rp.Close(); pageStream.Close(); //RankGameTime.aspx rq = System.Net.WebRequest.Create(domain + "/RankGameTime2.aspx"); rp = (System.Net.HttpWebResponse)rq.GetResponse(); pageStream = rp.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(pageStream)) { //读取 string tmp = sr.ReadToEnd(); //无参数的Ranking.html string path = HttpContext.Current.Server.MapPath(RootFilePath + "RankGameTime.html"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8)) { sw.Write(tmp); } } rq.Abort(); rp.Close(); pageStream.Close(); //RankMoney.aspx rq = System.Net.WebRequest.Create(domain + "/RankMoney2.aspx"); rp = (System.Net.HttpWebResponse)rq.GetResponse(); pageStream = rp.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(pageStream)) { //读取 string tmp = sr.ReadToEnd(); //无参数的Ranking.html string path = HttpContext.Current.Server.MapPath(RootFilePath + "RankMoney.html"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8)) { sw.Write(tmp); } } rq.Abort(); rp.Close(); pageStream.Close(); //RankOnLineTime.aspx rq = System.Net.WebRequest.Create(domain + "/RankOnLineTime2.aspx"); rp = (System.Net.HttpWebResponse)rq.GetResponse(); pageStream = rp.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(pageStream)) { //读取 string tmp = sr.ReadToEnd(); //无参数的Ranking.html string path = HttpContext.Current.Server.MapPath(RootFilePath + "RankOnLineTime.html"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8)) { sw.Write(tmp); } } rq.Abort(); rp.Close(); pageStream.Close(); //Ranking带参数的页面输出开始 System.Data.DataTable dt; object dtCache = HttpContext.Current.Cache.Get("GameIDList"); //BCST.Cache.BCSTCache.Default.Get<BCST.Cache.AspNetCache>("GameIDList"); if (dtCache == null) { //重新读取 dt = new BLL.Game().ListTGameNameInfo(0); HttpContext.Current.Cache.Insert("GameIDList", dt, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(12, 0, 0)); } else { dt = (System.Data.DataTable)dtCache; } foreach (System.Data.DataRow row in dt.Rows) { rq = System.Net.WebRequest.Create(domain + "/Ranking2.aspx?id=" + row["NameID"].ToString() + "&name=" + Server.UrlEncode(row["ComName"].ToString())); rp = (System.Net.HttpWebResponse)rq.GetResponse(); pageStream = rp.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(pageStream)) { //读取 string tmp = sr.ReadToEnd(); //无参数的Ranking.html string path = HttpContext.Current.Server.MapPath(RootFilePath + "Ranking_" + row["NameID"].ToString() + ".html"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8)) { sw.Write(tmp); } } rq.Abort(); rp.Close(); pageStream.Close(); } msg.Text = "全部生成成功!" + DateTime.Now; msg.ForeColor = System.Drawing.Color.Green; } catch (Exception ex) { msg.Text = "生成失败:" + ex.Message; } }
/// <summary> /// Init a Stream /// </summary> /// <param name="webRequest">WebRequest to connect to streaming API</param> /// <returns>The stream connected to Twitter Streaming API</returns> private static StreamReader init_webRequest(WebRequest webRequest) { StreamReader reader = null; HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); try { reader = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); } catch (ArgumentException ex) { if (ex.Message == "Stream was not readable.") { webRequest.Abort(); // Modified by Linvi } else throw ex; } return reader; }