// Simple WebRequest public string ExecuteWebRequest(HttpWebRequest webRequest) { try { var webRequestResult = GetWebRequestResultFromHttpClient(webRequest); if (!webRequestResult.IsSuccessStatusCode) { throw _exceptionHandler.TryLogFailedWebRequestResult(webRequestResult); } var stream = webRequestResult.ResultStream; if (stream != null) { // Getting the result var responseReader = new StreamReader(stream); return responseReader.ReadLine(); } // Closing the connection webRequest.Abort(); } catch (AggregateException aex) { var webException = aex.InnerException as WebException; var httpRequestMessageException = aex.InnerException as HttpRequestException; if (httpRequestMessageException != null) { webException = httpRequestMessageException.InnerException as WebException; } if (webException != null) { if (webRequest != null) { webRequest.Abort(); throw _exceptionHandler.TryLogWebException(webException, webRequest.RequestUri.AbsoluteUri); } throw webException; } throw; } catch (TimeoutException) { var twitterTimeoutException = _twitterTimeoutExceptionFactory.Create(new ConstructorNamedParameter("url", webRequest.RequestUri.AbsoluteUri)); if (_exceptionHandler.LogExceptions) { _exceptionHandler.AddTwitterException(twitterTimeoutException); } throw (Exception)twitterTimeoutException; } return null; }
private static System.Net.WebResponse Download(string url, int timeout) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); request.Timeout = timeout; request.ReadWriteTimeout = timeout; try { return(request.GetResponse()); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.Timeout) { request.Abort(); throw; } else { //debug string responseString; using (var sr = new System.IO.StreamReader(ex.Response.GetResponseStream())) { responseString = sr.ReadToEnd(); } ex.Response.Close(); throw new WebException(string.Format("ERROR: {0}", ((HttpWebResponse)ex.Response).StatusCode.ToString()), ex); } } catch (Exception) { request.Abort(); throw; } }
/// <summary> /// 根据URL获取返回数据 /// </summary> /// <returns></returns> public string Get(string uri, string encoding = "utf-8") { string strBuff = string.Empty; Uri httpURL = new Uri(uri); try { System.Net.HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL); HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse(); using (Stream respStream = httpResp.GetResponseStream()) { using (StreamReader respStreamReader = new StreamReader(respStream, Encoding.GetEncoding(encoding))) { strBuff = respStreamReader.ReadToEnd(); } } httpResp.Close(); httpReq.Abort(); } catch (Exception ex) { strBuff = string.Empty; } return(strBuff); }
public static void CheckUpdate() { kIRCVersionChecker.Init(); Updater = (HttpWebRequest)HttpWebRequest.Create(update_checkerurl); Updater_Response = (HttpWebResponse)Updater.GetResponse(); if (Updater_Response.StatusCode == HttpStatusCode.OK) { Rocket.Unturned.Logging.Logger.Log("kIRC: Contacting updater..."); Stream reads = Updater_Response.GetResponseStream(); byte[] buff = new byte[10]; reads.Read(buff, 0, 10); string ver = Encoding.UTF8.GetString(buff); ver = ver.ToLower().Trim(new[] { ' ', '\r', '\n', '\t' }).TrimEnd(new[] { '\0' }); if (ver == VERSION.ToLower().Trim()) { Rocket.Unturned.Logging.Logger.Log("kIRC: This plugin is using the latest version!"); } else { Rocket.Unturned.Logging.Logger.LogWarning("kIRC Warning: Plugin version mismatch!"); Rocket.Unturned.Logging.Logger.LogWarning("Current version: "+VERSION+", Latest version on repository is " + ver + "."); } } else { Rocket.Unturned.Logging.Logger.LogError("kIRC Error: Failed to contact updater."); } Updater.Abort(); Updater = null; Updater_Response = null; lastchecked = DateTime.Now; }
void HeartBeatHandler() { while( true ) { try { request = (HttpWebRequest)WebRequest.Create( URL ); request.Method = "POST"; request.Timeout = 15000; // 15s timeout request.ContentType = "application/x-www-form-urlencoded"; request.CachePolicy = new System.Net.Cache.RequestCachePolicy( System.Net.Cache.RequestCacheLevel.NoCacheNoStore ); byte[] formData = Encoding.ASCII.GetBytes( staticData + "&users=" + world.GetPlayerCount() ); request.ContentLength = formData.Length; using( Stream requestStream = request.GetRequestStream() ) { requestStream.Write( formData, 0, formData.Length ); requestStream.Flush(); } if( !hasReportedServerURL ) { using( WebResponse response = request.GetResponse() ) { using( StreamReader responseReader = new StreamReader( response.GetResponseStream() ) ) { world.config.ServerURL = responseReader.ReadToEnd().Trim(); } } request.Abort(); hash = world.config.ServerURL.Substring( world.config.ServerURL.LastIndexOf( '=' ) + 1 ); world.FireURLChange( world.config.ServerURL ); hasReportedServerURL = true; } } catch( Exception ex ) { world.log.Log( "HeartBeat: {0}", LogType.Error, ex.Message ); } try { request = (HttpWebRequest)WebRequest.Create( fListURL ); request.Method = "POST"; request.Timeout = 15000; // 15s timeout request.ContentType = "application/x-www-form-urlencoded"; request.CachePolicy = new System.Net.Cache.RequestCachePolicy( System.Net.Cache.RequestCacheLevel.NoCacheNoStore ); string requestString = staticData + "&users=" + world.GetPlayerCount() + "&hash=" + hash + "&motd=" + Server.UrlEncode( world.config.GetString( "MOTD" ) ) + "&server=fcraft" + "&players=" + world.GetPlayerListString(); byte[] formData = Encoding.ASCII.GetBytes( requestString ); request.ContentLength = formData.Length; using( Stream requestStream = request.GetRequestStream() ) { requestStream.Write( formData, 0, formData.Length ); requestStream.Flush(); } request.Abort(); } catch( Exception ex ) { world.log.Log( "HeartBeat: Error reporting to fList: {0}", LogType.Error, ex.Message ); } Thread.Sleep( Config.HeartBeatDelay ); } }
public async Task <IHttpWebResponse> GetResponseAsync(CancellationToken token) { try { using (token.Register(delegate { request.Abort(); }, false)) { Task <WebResponse> requestTask = request.GetResponseAsync(); System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)(await requestTask.ConfigureAwait(false)); if (token.IsCancellationRequested) { requestTask.ContinueWith(delegate(Task <WebResponse> task) { _ = task.Exception; }); return(new HttpWebResponse { ErrorCode = ErrorCode.RequestTimedOut }); } if (httpWebResponse == null) { return(new HttpWebResponse { ErrorCode = ErrorCode.NullResponse }); } return(new HttpWebResponse { ErrorCode = ErrorCode.NoError, Response = httpWebResponse, Headers = httpWebResponse.Headers }); } } catch (Exception ex) { WebException ex2 = (!(ex is AggregateException)) ? (ex as WebException) : (ex.InnerException as WebException); if (ex2 == null) { throw; } HttpStatusCode statusCode = HttpStatusCode.Unused; if (ex2.Status == WebExceptionStatus.ProtocolError) { statusCode = (ex2.Response as System.Net.HttpWebResponse).StatusCode; } return(new HttpWebResponse { ErrorCode = ErrorCode.WebExceptionThrown, ExceptionCode = ex2.Status, StatusCode = statusCode }); } }
/// <summary> /// Open Http file in a MemoryStream for read only. The HttpStream is copied in a MemoryStream. /// </summary> /// <param name="pStream">The ouput stream.</param> /// <param name="connectionGroupName">The connection group name to use for http requests.</param> private void OpenReadHttpFile(out System.IO.Stream pStream, string connectionGroupName) { pStream = null; FileInfo lDestFileInfo = new FileInfo(_destRemoteFile); try { System.Net.HttpWebRequest lRequestFileDl = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(_filePath); try { lRequestFileDl.ConnectionGroupName = connectionGroupName; System.Net.HttpWebResponse lResponseFileDl = (System.Net.HttpWebResponse)lRequestFileDl.GetResponse(); try { using (System.IO.FileStream lFileStream = lDestFileInfo.OpenWrite()) { using (System.IO.Stream lStream = lResponseFileDl.GetResponseStream()) { int i = 0; byte[] bytes = new byte[2048]; do { i = lStream.Read(bytes, 0, bytes.Length); lFileStream.Write(bytes, 0, i); } while (i != 0); lStream.Close(); } lFileStream.Close(); } } finally { lResponseFileDl.Close(); } } finally { try { lRequestFileDl.Abort(); } catch (NotImplementedException) { // Ignore the not implemented exception } } pStream = lDestFileInfo.OpenRead(); pStream.Seek(0, System.IO.SeekOrigin.Begin); } catch (Exception ex) { PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, ex.Message, "PIS.Ground.Core.Data.RemoteFileClass", ex, EventIdEnum.GroundCore); } }
/// <summary> /// Resettet den HttpRequest und bereitet ihn auf eine Verbindung vor /// </summary> protected void ResetHttpRequest(string url) { if (Request != null) { Request.Abort(); } Request = WebRequest.CreateHttp(url); Request.Credentials = new NetworkCredential(Credentials.Username, Credentials.Password); Request.UserAgent = "OwncloudClient for Windows Phone"; }
/// <summary> /// 获取URL上的HTML页面 /// </summary> /// <param name="URL">地址</param> /// <param name="Method">方式,使用POST或GET</param> /// <param name="usesession">是否需要SESSION</param> /// <returns>HTML代码</returns> public string GetHtml(string URL, bool usesession = false) { string Html = ""; try { myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL); myHttpWebRequest.ContentType = ConnType; myHttpWebRequest.KeepAlive = keepalive; myHttpWebRequest.Timeout = TOut; myHttpWebRequest.Method = "GET"; if (usesession) { myHttpWebRequest.CookieContainer = session; } if (useragent.ToString().Trim() != "") { myHttpWebRequest.UserAgent = useragent; } if (refer.ToString().Trim() != "") { myHttpWebRequest.Referer = refer; } if (sendchunked) { myHttpWebRequest.SendChunked = true; myHttpWebRequest.TransferEncoding = TransferEncoding; } //接收 myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); iStatCode = (int)myHttpWebResponse.StatusCode; RConnType = myHttpWebResponse.ContentType; ConnCharSet = myHttpWebResponse.CharacterSet; ConnEncode = myHttpWebResponse.ContentEncoding; if (iStatCode == 200) { StreamReader reader = new StreamReader(myHttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding(ConnCharSet)); Html = reader.ReadToEnd(); reader.Close(); } else { ErrMsg = "HTTP ERR:" + iStatCode.ToString(); } myHttpWebResponse.Close(); myHttpWebRequest.Abort(); } catch (Exception ex) { ErrMsg = ex.Message; } return(Html); }
public override void Close() { bool previously_closed = this.IsClosed; if (http_request != null) { http_request.Abort(); http_request = null; } this.IsClosed = true; if (!previously_closed) { InvokeClosedEvent(); } }
/// <summary> /// 下载文件 /// </summary> /// <param name="pURL">下载文件地址</param> /// <param name="Filename">下载后另存为(全路径)</param> public static bool HttpDownloadFile(string pURL, string pFilename, out string pError) { try { pError = null; if (pURL == null || pURL.Length <= 0) { pError = "下载地址为空!"; return(false); } else { //if (!File.Exists(pFilename)) //{ ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(pURL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(pFilename, System.IO.FileMode.Create); byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { so.Write(by, 0, osize); osize = st.Read(by, 0, (int)by.Length); } so.Close(); st.Close(); myrp.Close(); Myrq.Abort(); return(true); //} //else //{ // pError = "下载保存的路径不存在!"; // return true; //} } } catch (System.Exception ex) { pError = "[pFilename:" + pFilename + " pURL:" + pURL + "]:" + ex.Message; return(false); } }
/// <summary> /// 下载Url文件类 /// </summary> /// <param name="downLoadUrl">文件的url路径</param> /// <param name="saveFolder">需要保存在本地的路径</param> /// <param name="saveFullName">需要保存在本地的文件名</param> /// <param name="saveFullName">需要保存在本地的文件类型</param> /// <returns></returns> public static bool DownloadFile(string downLoadUrl, string saveFolder, string saveName, string FolderType) { bool flagDown = false; System.Net.HttpWebRequest httpWebRequest = null; try { //根据url获取远程文件流 httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downLoadUrl); System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); System.IO.Stream sr = httpWebResponse.GetResponseStream(); //创建文件侠 if (!Directory.Exists(saveFolder)) { Directory.CreateDirectory(saveFolder); } //创建本地文件写入流 System.IO.Stream sw = new System.IO.FileStream(saveFolder + saveName + FolderType, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = sr.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; sw.Write(by, 0, osize); osize = sr.Read(by, 0, (int)by.Length); } System.Threading.Thread.Sleep(100); flagDown = true; sw.Close(); sr.Close(); } finally { if (httpWebRequest != null) { httpWebRequest.Abort(); } } return(flagDown); }
/// <summary> 检测WebService是否可用 </summary> public static bool IsWebServiceAvaiable(string url) { bool bRet = false; Net.HttpWebRequest myHttpWebRequest = null; try { System.GC.Collect(); myHttpWebRequest = (Net.HttpWebRequest)Net.WebRequest.Create(url); myHttpWebRequest.Timeout = 60000; myHttpWebRequest.KeepAlive = false; myHttpWebRequest.ServicePoint.ConnectionLimit = 200; using (Net.HttpWebResponse myHttpWebResponse = (Net.HttpWebResponse)myHttpWebRequest.GetResponse()) { bRet = true; if (myHttpWebResponse != null) { myHttpWebResponse.Close(); } } } catch (Net.WebException e) { Common.LogHelper.Instance.WriteError(String.Format("网络连接错误 : {0}", e.Message)); } catch (Exception ex) { Common.LogHelper.Instance.WriteError(ex.Message + "|" + ex.StackTrace); } finally { if (myHttpWebRequest != null) { myHttpWebRequest.Abort(); myHttpWebRequest = null; } } return(bRet); }
public static Connection ConnectOverHttpProxy(string remoteHost, int remotePort) { if (!HttpProxy.Exists) { throw new InvalidOperationException("Http Proxy has not been set."); } int availableLocalPort = Server.GetAvailableLocalEndPoint().Port; Server fakeProxy = Server.Start(IPAddress.Parse("127.0.0.1"), availableLocalPort); Console.WriteLine("\r\nConnectOverHttpProxy: Fake server listening on port {0}", availableLocalPort); TunnelWaitHandle taskCompletedEvent = new TunnelWaitHandle(); fakeProxy.SetObserver(new WebProxyServerObserver(taskCompletedEvent)); System.Net.HttpWebRequest webRequest = HttpWebRequest.Create("https://" + remoteHost + ":" + remotePort) as HttpWebRequest; webRequest.Proxy = HttpProxy.GenerateLocalProxy(availableLocalPort); webRequest.KeepAlive = false; webRequest.BeginGetResponse(null, null); taskCompletedEvent.WaitOne(); webRequest.Abort(); webRequest = null; fakeProxy.Stop(); if (taskCompletedEvent.Result == null) { throw new System.Exception("Could not connect to remote host"); } Console.WriteLine("nConnectOverHttpProxy: Connected to external net!"); return(taskCompletedEvent.Result as Connection); }
//private void DownFile() //{ // //获取文件路径 // string file_url = Request.QueryString["url"]; // if (file_url == null) // { // return; // } // string ext_name = Path.GetExtension(file_url); // string file_name = Path.GetFileName(file_url); // //组织存储路径和存储文件名 // string up_folder = System.Configuration.ConfigurationManager.AppSettings["hj_up_img"].ToString(); // up_folder = up_folder + HJ_DAL.ImgFolder._cls_space; // string time_span = HJ_DAL.ImgFolder.GetTimeStamp(); // //获取远程文件的数据流 // FileStream fs = new FileStream(up_folder + time_span + ext_name, FileMode.Create); // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(file_url); // HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Stream stream = response.GetResponseStream(); // int bufferSize = 2048; // byte[] bytes = new byte[bufferSize]; // try // { // int length = stream.Read(bytes, 0, bufferSize); // while (length > 0) // { // fs.Write(bytes, 0, length); // length = stream.Read(bytes, 0, bufferSize); // } // stream.Close(); // fs.Close(); // response.Close(); // } // catch (Exception ex) // { // return; // } //} /// <summary> /// 下载文件 /// </summary> /// <param name="URL">下载文件地址</param> /// <param name="dic">下载后的存放地址绝对路径 如:c:\122\</param> /// <param name="Filename">文件名(没后辍) 如:123</param> public static string DownloadFile(string URL, string dic, string fileName) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); request.Method = "GET"; request.ProtocolVersion = HttpVersion.Version10; request.KeepAlive = false; //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; request.Timeout = 30000; System.Net.HttpWebResponse response = null; try { response = (System.Net.HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); System.Drawing.Image img = System.Drawing.Image.FromStream(stream); fileName = dic + fileName + ".jpg"; img.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg); stream.Close(); response.Close(); img.Dispose(); stream.Dispose(); return(fileName); } catch (System.Exception) { return(""); } finally { if (response != null) { response.Close(); } if (request != null) { request.Abort(); } } }
/// <summary> /// 下载文件 /// </summary> /// <param name="downLoadUrl">文件的url路径</param> /// <param name="saveFullName">需要保存在本地的路径(包含文件名)</param> /// <returns></returns> public static bool DownloadFile(string downLoadUrl, string saveFullName) { bool flagDown = false; System.Net.HttpWebRequest httpWebRequest = null; try { //根据url获取远程文件流 httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downLoadUrl); System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); System.IO.Stream sr = httpWebResponse.GetResponseStream(); //创建本地文件写入流 System.IO.Stream sw = new System.IO.FileStream(saveFullName, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = sr.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; sw.Write(by, 0, osize); osize = sr.Read(by, 0, (int)by.Length); } System.Threading.Thread.Sleep(100); flagDown = true; sw.Close(); sr.Close(); } catch (System.Exception) { if (httpWebRequest != null) httpWebRequest.Abort(); } return flagDown; }
//body是要传递的参数,格式"roleId=1&uid=2" //post的cotentType填写: //"application/x-www-form-urlencoded" //soap填写:"text/xml; charset=utf-8" public static string PostHttp(string url, string body, string contentType) { string responseContent = string.Empty; try { if (contentType == "" || contentType == null) { contentType = "application/x-www-form-urlencoded"; } System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); httpWebRequest.ContentType = contentType; httpWebRequest.Method = "POST"; httpWebRequest.Headers.Add("Timestamp", Convert.ToString(ConvertDateTimeInt(DateTime.Now))); httpWebRequest.ReadWriteTimeout = 30 * 1000; byte[] btBodys = Encoding.UTF8.GetBytes(body); httpWebRequest.ContentLength = btBodys.Length; httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length); System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); System.IO.StreamReader streamReader = new System.IO.StreamReader(httpWebResponse.GetResponseStream()); responseContent = streamReader.ReadToEnd(); httpWebResponse.Close(); streamReader.Close(); httpWebRequest.Abort(); httpWebResponse.Close(); } catch (Exception ex) { } return(responseContent); }
public static string GetIP() { Uri uri = new Uri("http://www.ikaka.com/ip/index.asp"); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = 0; req.CookieContainer = new System.Net.CookieContainer(); req.GetRequestStream().Write(new byte[0], 0, 0); System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)(req.GetResponse()); StreamReader rs = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("GB18030")); string s = rs.ReadToEnd(); rs.Close(); req.Abort(); res.Close(); System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, @"IP:\[(?<IP>[0-9\.]*)\]"); if (m.Success) { return(m.Groups["IP"].Value); } return(string.Empty); }
public HTTPPost(Uri Url, Dictionary<string, string> Parameters) { StringBuilder respBody = new StringBuilder(); // TRY RECONFIG TO A URL TYPE CONNECTION request = (HttpWebRequest)HttpWebRequest.Create(Url); // request.UserAgent = "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1C10 Safari/419.3"; request.UserAgent = "4SqLite 20110803"; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.AllowWriteStreamBuffering = true; request.Timeout = 10000; string content = "?"; foreach (string k in Parameters.Keys) { content += k + "=" + Parameters[k] + "&"; } content = content.TrimEnd(new char[] { '&' }); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] byte1 = encoding.GetBytes(content); request.ContentLength = byte1.Length; byte[] buf = new byte[8192]; Stream oOutStream = null; int tmp = ServicePointManager.DefaultConnectionLimit; try { // send the Post oOutStream = request.GetRequestStream(); } catch { MessageBox.Show("Oops! We couldn't send data to the Internet. Try again later.", "HttpPost: Request error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); } finally { if (oOutStream != null) { oOutStream.Write(byte1, 0, byte1.Length); //Send it oOutStream.Close(); } } try { // get the response response = (HttpWebResponse)request.GetResponse(); Stream respStream = response.GetResponseStream(); int count = 0; do { count = respStream.Read(buf, 0, buf.Length); if (count != 0) respBody.Append(Encoding.ASCII.GetString(buf, 0, count)); } while (count > 0); respStream.Close(); ResponseBody = respBody.ToString(); EscapedBody = GetEscapedBody(); } catch { MessageBox.Show("Oops! We couldn't get data from the Internet. Try again later.", "HttpPost: Response error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); ResponseBody = "No Server Response"; } finally { StatusCode = GetStatusLine(); Headers = GetHeaders(); if (response != null) { response.Close(); } request.Abort(); } /* try { using (Stream rs = request.GetRequestStream()) { rs.Write(byte1, 0, byte1.Length); rs.Close(); response = (HttpWebResponse)request.GetResponse(); Stream respStream = response.GetResponseStream(); int count = 0; do { count = respStream.Read(buf, 0, buf.Length); if (count != 0) respBody.Append(Encoding.ASCII.GetString(buf, 0, count)); } while (count > 0); respStream.Close(); ResponseBody = respBody.ToString(); EscapedBody = GetEscapedBody(); StatusCode = GetStatusLine(); Headers = GetHeaders(); response.Close(); } } catch { MessageBox.Show("Oops! We couldn't post any data to the Internet. Try again later.", "HttpPOST: Response error", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1); } */ }
private void TransmitQueue() { int num_tracks_transmitted; // save here in case we're interrupted before we complete // the request. we save it again when we get an OK back // from the server queue.Save(); next_interval = DateTime.MinValue; if (post_url == null || !connected) { return; } StringBuilder sb = new StringBuilder(); sb.AppendFormat("s={0}", session_id); sb.Append(queue.GetTransmitInfo(out num_tracks_transmitted)); current_web_req = (HttpWebRequest)WebRequest.Create(post_url); current_web_req.UserAgent = LastfmCore.UserAgent; current_web_req.Method = "POST"; current_web_req.ContentType = "application/x-www-form-urlencoded"; current_web_req.ContentLength = sb.Length; //Console.WriteLine ("Sending {0} ({1} bytes) to {2}", sb.ToString (), sb.Length, post_url); TransmitState ts = new TransmitState(); ts.Count = num_tracks_transmitted; ts.StringBuilder = sb; state = State.WaitingForRequestStream; current_async_result = current_web_req.BeginGetRequestStream(TransmitGetRequestStream, ts); if (!(current_async_result.AsyncWaitHandle.WaitOne(TIME_OUT, false))) { if (log.IsWarnEnabled) { log.Warn("Audioscrobbler upload failed." + " The request timed out and was aborted"); } next_interval = DateTime.Now + new TimeSpan(0, 0, RETRY_SECONDS); hard_failures++; state = State.Idle; current_web_req.Abort(); } }
/// <summary> /// Efetua o download do instalador do aplicativo /// </summary> /// <remarks> /// Autor: Wandrey Mundin Ferreira /// Date: 20/05/2010 /// </remarks> private void Download() { using (WebClient Client = new WebClient()) { try { // Desmarcar o flag Cancelado = false; // Criar um pedido do arquivo que será baixado webRequest = (HttpWebRequest)WebRequest.Create(URL); // Definir dados da conexao do proxy if (ConfiguracaoApp.Proxy) { webRequest.Proxy = NFe.Components.Proxy.DefinirProxy(ConfiguracaoApp.ProxyServidor, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyPorta, ConfiguracaoApp.DetectarConfiguracaoProxyAuto); } // Atribuir autenticação padrão para a recuperação do arquivo webRequest.Credentials = CredentialCache.DefaultCredentials; // Obter a resposta do servidor webResponse = (HttpWebResponse)webRequest.GetResponse(); // Perguntar ao servidor o tamanho do arquivo que será baixado Int64 fileSize = webResponse.ContentLength; // Abrir a URL para download strResponse = Client.OpenRead(URL); // Criar um novo arquivo a partir do fluxo de dados que será salvo na local disk strLocal = new FileStream(LocalArq, FileMode.Create, FileAccess.Write, FileShare.None); // Ele irá armazenar o número atual de bytes recuperados do servidor int bytesSize = 0; // Um buffer para armazenar e gravar os dados recuperados do servidor byte[] downBuffer = new byte[2048]; // Loop através do buffer - Até que o buffer esteja vazio while (Cancelado == false && (bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { // Gravar os dados do buffer no disco rigido strLocal.Write(downBuffer, 0, bytesSize); // Invocar um método para atualizar a barra de progresso this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize }); } if (Cancelado) MetroFramework.MetroMessageBox.Show(null, "Atualização foi cancelada!", ""); else this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { fileSize, fileSize }); } catch (IOException ex) { MetroFramework.MetroMessageBox.Show(null, "Ocorreu um erro ao tentar fazer o download do instalador do aplicativo.\r\n\r\nErro: " + ex.Message, ""); } catch (WebException ex) { MetroFramework.MetroMessageBox.Show(null, "Ocorreu um erro ao tentar fazer o download do instalador do aplicativo.\r\n\r\nErro: " + ex.Message, ""); } catch (Exception ex) { MetroFramework.MetroMessageBox.Show(null, "Ocorreu um erro ao tentar fazer o download do instalador do aplicativo.\r\n\r\nErro: " + ex.Message, ""); } finally { // Encerrar as streams if (strResponse != null) strResponse.Close(); if (strLocal != null) strLocal.Close(); webRequest.Abort(); webResponse.Close(); } } }
/// <summary> /// HTTP/HTTPS的POST方法获取HttpWebResponse /// </summary> /// <param name="Url">要POST数据的网址</param> /// <param name="PostData">POST的数据</param> /// <returns>HttpWebResponse</returns> protected void PostResponse(String Url, String PostData, ref HttpWebResponse Response, ref HttpWebRequest rqst, String[] headers, int level = 0) { //如果使用代理https变为http //if (Url.ToLower().Contains("https://") && proxy.Address != null) // Url = "http" + Url.Substring(5); Uri uri = new Uri(Url); //设置HTTPS方式 if (Url.ToLower().Contains("https://")) ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult; //将POST数据按encoding编码转换为二进制数据 byte[] bytes = encoding.GetBytes(PostData); //构造HTTP头 rqst = (HttpWebRequest)WebRequest.Create(uri); rqst.KeepAlive = true; rqst.ServicePoint.Expect100Continue = false; rqst.AllowAutoRedirect = false; rqst.Accept = "*/*"; rqst.Headers.Add("Accept-Language: zh-CN"); if (reffer != null) { try { rqst.Referer = reffer.AbsoluteUri; } catch { } } rqst.ContentType = "application/x-www-form-urlencoded"; rqst.Headers.Add("Accept-Encoding: gzip,deflate"); rqst.UserAgent = UserAgent; rqst.ContentLength = bytes.Length; rqst.Headers.Add("Cache-Control: no-cache"); foreach (String s in headers) { rqst.Headers.Add(s); } rqst.CookieContainer = Cookies; rqst.Method = "POST"; if (proxy.Address != null) { rqst.ProtocolVersion = HttpVersion.Version10; //启用代理 rqst.UseDefaultCredentials = true; rqst.Proxy = proxy; } //记录当前访问页以便下次访问设置Reffer reffer = uri; //POST数据 using (Stream RequestStream = rqst.GetRequestStream()) { RequestStream.Write(bytes, 0, bytes.Length); RequestStream.Close(); } //获取POST结果 Response = (HttpWebResponse)rqst.GetResponse(); //更新COOKIE foreach (Cookie ck in Response.Cookies) { Cookies.Add(ck); } //防止无限循环跳转 if (level < 5) { //自动重定向网页 if (Response.Headers["Location"] != null) { reffer = null; Response.Close(); rqst.Abort(); String location = Response.Headers["Location"]; if (!location.Contains("://")) location = uri.Scheme + "://" + uri.Authority + location; GetResponse(location, ref Response, ref rqst, ++level); } else if (Response.ResponseUri != uri) { Response.Close(); rqst.Abort(); GetResponse(Response.ResponseUri.AbsoluteUri, ref Response, ref rqst, ++level); } } }
/// <summary> /// Reads the information received from the Twitter real-time data stream. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> private void ReadResponseStream(HttpWebRequest request, HttpWebResponse response) { byte[] buffer = new byte[65536]; using (Stream stream = response.GetResponseStream()) { while (this.InternalConnectionStatus == ConnectionStatus.Connected) { int read = stream.Read(buffer, 0, buffer.Length); this._dateReceivedInLastSecond += read; UTF8Encoding encoding = new UTF8Encoding(); string data = encoding.GetString(buffer, 0, read); ParseResponseChunk(data); } // need to call request.Abort or the the thread will block at the end of // the using block. request.Abort(); } }
void ThreadableResumeDownload(string url, Action <int, int> stepCallback, Action errorCallback, Action successCallback) { //string tmpFullPath = TmpDownloadPath; //根据实际情况设置 System.IO.FileStream downloadFileStream; //打开上次下载的文件或新建文件 long lStartPos = 0; if (System.IO.File.Exists(TmpDownloadPath)) { downloadFileStream = System.IO.File.OpenWrite(TmpDownloadPath); lStartPos = downloadFileStream.Length; downloadFileStream.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针 CDebug.LogConsole_MultiThread("Resume.... from {0}", lStartPos); } else { downloadFileStream = new System.IO.FileStream(TmpDownloadPath, System.IO.FileMode.Create); lStartPos = 0; } System.Net.HttpWebRequest request = null; //打开网络连接 try { request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); if (lStartPos > 0) { request.AddRange((int)lStartPos); //设置Range值 } CDebug.LogConsole_MultiThread("Getting Response : {0}", url); //向服务器请求,获得服务器回应数据流 using (var response = request.GetResponse()) // TODO: Async Timeout { CDebug.LogConsole_MultiThread("Getted Response : {0}", url); if (IsFinished) { throw new Exception(string.Format("Get Response ok, but is finished , maybe timeout! : {0}", url)); } else { var totalSize = (int)response.ContentLength; if (totalSize <= 0) { totalSize = int.MaxValue; } using (var ns = response.GetResponseStream()) { CDebug.LogConsole_MultiThread("Start Stream: {0}", url); int downSize = (int)lStartPos; int chunkSize = 10240; byte[] nbytes = new byte[chunkSize]; int nReadSize = (int)lStartPos; while ((nReadSize = ns.Read(nbytes, 0, chunkSize)) > 0) { if (IsFinished) { throw new Exception("When Reading Web stream but Downloder Finished!"); } downloadFileStream.Write(nbytes, 0, nReadSize); downSize += nReadSize; stepCallback(totalSize, downSize); } stepCallback(totalSize, totalSize); request.Abort(); downloadFileStream.Close(); } } } CDebug.LogConsole_MultiThread("下载完成: {0}", url); if (File.Exists(_SavePath)) { File.Delete(_SavePath); } File.Move(TmpDownloadPath, _SavePath); } catch (Exception ex) { CDebug.LogConsole_MultiThread("下载过程中出现错误:" + ex.ToString()); downloadFileStream.Close(); if (request != null) { request.Abort(); } try { if (File.Exists(TmpDownloadPath)) { File.Delete(TmpDownloadPath); // delete temporary file } } catch (Exception e) { CDebug.LogConsole_MultiThread(e.Message); } errorCallback(); } successCallback(); }
public static bool Pump(Beat type) { if (staticVars == null) Init(); // default information to send string postVars = staticVars; string url = "http://www.classicube.net/heartbeat.jsp"; try { int hidden = 0; // append additional information as needed switch (type) { case Beat.ClassiCube: postVars += "&salt=" + Server.salt2; goto default; case Beat.Minecraft: url = "https://minecraft.net/heartbeat.jsp"; postVars += "&salt=" + Server.salt; goto default; default: postVars += "&users=" + (Player.number - hidden); break; } request = (HttpWebRequest)WebRequest.Create(new Uri(url + "?" + postVars)); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); byte[] formData = Encoding.ASCII.GetBytes(postVars); request.ContentLength = formData.Length; request.Timeout = 15000; try { using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(formData, 0, formData.Length); requestStream.Close(); } } catch (WebException e) { if (e.Status == WebExceptionStatus.Timeout) { throw new WebException("Failed during request.GetRequestStream()", e.InnerException, e.Status, e.Response); } } if (hash == null) { using (WebResponse response = request.GetResponse()) { using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) { string line = responseReader.ReadLine(); hash = line.Substring(line.LastIndexOf('=') + 1); serverURL = line; Server.s.UpdateUrl(serverURL); Server.s.Log("URL saved to text/externalurl.txt..."); File.WriteAllText("text/externalurl.txt", serverURL); } } } } catch (WebException e) { if (e.Status == WebExceptionStatus.Timeout) { Server.s.Log(string.Format("Timeout: {0}", type)); } Server.ErrorLog(e); } catch (Exception e) { Server.s.Log(string.Format("Error reporting to {0}", type)); Server.ErrorLog(e); return false; } finally { request.Abort(); } return true; }
public static async Task<string> DownloadWebsiteAsStringAsync(HttpWebRequest req) { string response = string.Empty; using (HttpWebResponse resp = (HttpWebResponse)(await req.GetResponseAsyncExt().ConfigureAwait(false))) { if (resp == null) { if (req != null) { req.Abort(); } } else { if (resp.StatusCode == HttpStatusCode.OK) { using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { try { response = await sr.ReadToEndAsync().ConfigureAwait(false); } catch (IOException) { response = string.Empty; } } } else { string errorMessage = string.Format("Getting website {0} failed with code: {1}, desc: {2}", req.RequestUri.AbsoluteUri, resp.StatusCode.ToString(), resp.StatusDescription); await Utils.LogMessageAsync(errorMessage).ConfigureAwait(false); } } } return response; }
public static string DownloadWebsiteAsString(HttpWebRequest req) { string response = string.Empty; using (HttpWebResponse resp = (HttpWebResponse)req.GetResponseExt()) { if (resp == null) { if (req != null) { req.Abort(); } } else { if (resp.StatusCode == HttpStatusCode.OK) { using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { try { response = sr.ReadToEnd(); } catch (IOException) { response = string.Empty; } } } else { string errorMessage = string.Format("Getting website {0} failed with code {1}", req.RequestUri.AbsoluteUri, resp.StatusCode.ToString()); Utils.LogMessage(errorMessage); } } } return response; }
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Abort(); }
public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(null, null); _savedHttpWebRequest.Abort(); }
public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); WebException wex = _savedResponseException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); }
public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), null); _savedHttpWebRequest.Abort(); Assert.Equal(1, _responseCallbackCallCount); }
internal static IEnumerable <Object.QuoteData> Request(string url, string data, Encoding encoding) { string cachePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\CachedData\"; string cacheFileName = cachePath + data.Substring(data.LastIndexOf('|') + 1) + ".dataCache"; Stack <Object.QuoteData> datas = getCachedData(cacheFileName, true); // true indicates always use current cache. if (datas != null) { return(datas); } else { datas = new Stack <Object.QuoteData>(); } #if DEBUG int retryCounter = 10; #else int retryCounter = 3; #endif System.Net.HttpWebRequest request = null; System.Net.HttpWebResponse response = null; var bs = encoding.GetBytes(data); url = url.ToLower(); RETRY: try { request = (System.Net.HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = bs.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(bs, 0, bs.Length); stream.Flush(); } response = (System.Net.HttpWebResponse)request.GetResponse(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); if (retryCounter > 0) { request.Abort(); retryCounter--; goto RETRY; } } if ((response == null || response.StatusCode != HttpStatusCode.OK) && retryCounter > 0) { request.Abort(); retryCounter--; goto RETRY; } StreamWriter dataWriter = null; try { using (System.IO.Stream stream = response.GetResponseStream()) { // if it's not possible to open the file for writing, then flag it or just retrieve without caching. try { dataWriter = File.CreateText(cacheFileName); } catch (Exception ex) { dataWriter = null; // If a data cache is not desired, comment the following "if" and "throw statements if (ex is System.UnauthorizedAccessException) { throw new Exception("To cache data, Write Access required for path: " + cacheFileName, ex); } } using (StreamReader sr = new StreamReader(stream, encoding)) { // skip headers string line = sr.ReadLine(); if (dataWriter != null) { dataWriter.WriteLine(line); line = sr.ReadLine(); dataWriter.WriteLine(line); } else { sr.ReadLine(); } for (line = sr.ReadLine(); line != null; line = sr.ReadLine()) { if (dataWriter != null) { dataWriter.WriteLine(line); } datas.Push(ParseLine(line)); } } } } catch (Exception ex) { if (retryCounter <= 0 || response == null) { datas = getCachedData(cacheFileName, true); if (datas == null) { System.Diagnostics.Debug.WriteLine("Financial data is not available at this time."); System.Diagnostics.Debug.WriteLine(ex.Message); throw ex; } } } finally { if (dataWriter != null) { dataWriter.Close(); dataWriter.Dispose(); dataWriter = null; } } return(datas); }
/// <summary> /// HTTP文件下载 /// </summary> /// <param name="URL">文件HTTP地址,HTTP地址不支持中文字符,中午字符需要做URL编码</param> /// <param name="SavePath">保存路径</param> /// <param name="FileName">保存文件名,为空则</param> /// <param name="usesession">是否需要SESSION</param> /// <param name="ReDownLoad">是否覆盖原文件</param> /// <param name="BufferSize">缓存大小</param> /// <returns>执行结果</returns> public bool DownLoad(string URL, string SavePath, string FileName = "", bool usesession = false, bool ReDownLoad = false, int BufferSize = 4096) { try { if (URL == null || FileName == null || SavePath == null) { ErrMsg = "REF unvalid"; return(false); } else if (URL.Trim() == "" || FileName.Trim() == "" || SavePath.Trim() == "") { ErrMsg = "REF unvalid"; return(false); } else { bool res = false; DirectoryInfo di = new DirectoryInfo(SavePath); if (!di.Exists) { di.Create(); } FileInfo fi; if (FileName.Trim() != "") { fi = new FileInfo(SavePath + "\\" + FileName); } else { FileName = URL.Substring(URL.LastIndexOf("/") + 1); fi = new FileInfo(SavePath + "\\" + FileName); } long index = 0; System.IO.FileStream fs = null; try { myHttpWebRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(URL); myHttpWebRequest.KeepAlive = keepalive; myHttpWebRequest.Timeout = TOut; if (usesession) { myHttpWebRequest.CookieContainer = session; } if (useragent.Trim() != "") { myHttpWebRequest.UserAgent = useragent; } if (refer.ToString().Trim() != "") { myHttpWebRequest.Referer = refer; } if (fi.Exists) { if (ReDownLoad) { fi.Delete(); fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Create); } else { index = fi.Length; fs = System.IO.File.OpenWrite(fi.FullName); fs.Seek(index, System.IO.SeekOrigin.Begin); myHttpWebRequest.AddRange((int)index); } } else { fs = new System.IO.FileStream(fi.FullName, System.IO.FileMode.Create); } myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); iStatCode = (int)myHttpWebResponse.StatusCode; if (iStatCode == 200 || iStatCode == 206) { Stream myStream = myHttpWebResponse.GetResponseStream(); //定义一个字节数据 byte[] btContent = new byte[BufferSize]; int intSize = 0; intSize = myStream.Read(btContent, 0, btContent.Length); while (intSize > 0) { fs.Write(btContent, 0, intSize); intSize = myStream.Read(btContent, 0, btContent.Length); } //关闭流 myStream.Close(); myHttpWebResponse.Close(); myHttpWebRequest.Abort(); res = true; } else { myHttpWebResponse.Close(); myHttpWebRequest.Abort(); ErrMsg = "HTTP ERR:" + iStatCode.ToString(); res = false; } } catch (Exception ex) { ErrMsg = ex.Message; res = false; } finally { fs.Close(); fs = null; } return(res); } } catch (Exception ex) { ErrMsg = ex.Message; return(false); } }
/// <summary> /// Used by the worker thread to start the request /// </summary> public void Start() { try { // Create the request request = (HttpWebRequest)System.Net.WebRequest.Create(URL); request.Method = Method; request.Credentials = CredentialCache.DefaultCredentials; request.Proxy = null; request.KeepAlive = false; request.Timeout = (int)Math.Round((Timeout == 0f ? WebRequests.Timeout : Timeout) * 1000f); request.ServicePoint.MaxIdleTime = request.Timeout; request.ServicePoint.Expect100Continue = ServicePointManager.Expect100Continue; request.ServicePoint.ConnectionLimit = ServicePointManager.DefaultConnectionLimit; // Optional request body for post requests var data = new byte[0]; if (Body != null) { data = Encoding.UTF8.GetBytes(Body); request.ContentLength = data.Length; request.ContentType = "application/x-www-form-urlencoded"; } if (RequestHeaders != null) request.SetRawHeaders(RequestHeaders); // Perform DNS lookup and connect (blocking) if (data.Length > 0) { request.BeginGetRequestStream(result => { if (request == null) return; try { // Write request body using (var stream = request.EndGetRequestStream(result)) stream.Write(data, 0, data.Length); } catch (Exception ex) { ResponseText = ex.Message.Trim('\r', '\n', ' '); if (request != null) request.Abort(); OnComplete(); return; } WaitForResponse(); }, null); } else { WaitForResponse(); } } catch (Exception ex) { ResponseText = ex.Message.Trim('\r', '\n', ' '); Interface.Oxide.LogException(string.Format("Web request produced exception (Url: {0})", URL), ex); if (request != null) request.Abort(); OnComplete(); } }
/// <summary> /// 提交表单并返回URL上的HTML页面 /// </summary> /// <param name="URL">地址</param> /// <param name="Postdata">提交表单数据</param> /// <param name="usesession">是否需要SESSION</param> /// <returns>HTML代码</returns> public string PostHtml(string URL, String Postdata, bool usesession) { string Html = ""; try { myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL); myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; myHttpWebRequest.KeepAlive = keepalive; myHttpWebRequest.Timeout = TOut; myHttpWebRequest.Method = "Post"; if (usesession) { myHttpWebRequest.CookieContainer = session; } if (useragent.Trim() != "") { myHttpWebRequest.UserAgent = useragent; } if (refer.ToString().Trim() != "") { myHttpWebRequest.Referer = refer; } if (sendchunked) { myHttpWebRequest.SendChunked = true; myHttpWebRequest.TransferEncoding = TransferEncoding; } if (CharSet.Trim() != "") { byte[] data = Encoding.GetEncoding(CharSet.Trim()).GetBytes(Postdata); myHttpWebRequest.ContentLength = data.Length; Stream newStream = myHttpWebRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); } else { byte[] data = Encoding.ASCII.GetBytes(Postdata); myHttpWebRequest.ContentLength = data.Length; Stream newStream = myHttpWebRequest.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); } //接收 myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); iStatCode = (int)myHttpWebResponse.StatusCode; RConnType = myHttpWebResponse.ContentType; ConnCharSet = myHttpWebResponse.CharacterSet; ConnEncode = myHttpWebResponse.ContentEncoding; if (iStatCode == 200) { StreamReader reader = new StreamReader(myHttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding(ConnCharSet)); Html = reader.ReadToEnd(); reader.Close(); } else { ErrMsg = "HTTP ERR:" + iStatCode.ToString(); } myHttpWebResponse.Close(); myHttpWebRequest.Abort(); } catch (Exception ex) { ErrMsg = ex.Message; } return(Html); }
public void Download() { Int64 fileSize = 0; string fullSavePath = _SavePath.TrimEnd('\\') + @"\" + _BeatInfo.Artist + " - " + _BeatInfo.Title; try { if (m_EventStopThread.WaitOne(0, true)) { throw new Exception(); } // get beat if (_BeatInfo.Beat.Length == 0 || _BeatInfo.Beat == null) { string webContent; Match matchURL; if (_BeatInfo.Site == "sannhac.com") { // get content + ungzip webContent = GlobalCode.GetContent(_BeatInfo.Link, true); matchURL = Regex.Match(webContent, @"<div class=""ttct\-download""><a href=""([^""]+)""", RegexOptions.IgnoreCase); if (matchURL.Groups.Count != 0) { _BeatInfo.Beat = matchURL.Groups[1].Value; } } // zing else { webContent = GlobalCode.GetContent("http://star.zing.vn/includes/fnGetSongInfo.php?id=" + _BeatInfo.Link); matchURL = Regex.Match(webContent, @"<karaokelink>([^<]+)</karaokelink>", RegexOptions.IgnoreCase); if (matchURL.Groups.Count != 0) { _BeatInfo.Beat = matchURL.Groups[1].Value; } } } // download beat if (_BeatInfo.Beat.Length == 0 || _BeatInfo.Beat == null) { OnError(); return; } if (_BeatInfo.Beat.EndsWith(".mp3", StringComparison.CurrentCultureIgnoreCase) || _BeatInfo.Beat.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase)) { _BeatInfo.BeatType = ".mp3"; } else { _BeatInfo.BeatType = ".swf"; } if (m_EventStopThread.WaitOne(0, true)) { throw new Exception(); } // DOWNLOAD using (WebClient wcDownload = new WebClient()) { webRequest = (HttpWebRequest) HttpWebRequest.Create(_BeatInfo.Beat); webRequest.Credentials = CredentialCache.DefaultCredentials; webRequest.KeepAlive = false; //webRequest.Timeout = 30000; webResponse = (HttpWebResponse)webRequest.GetResponse(); if (m_EventStopThread.WaitOne(0, true)) { throw new Exception(); } fileSize = webResponse.ContentLength; // Open the URL for download strResponse = webResponse.GetResponseStream(); OnUpdateProgress(new UpdateProgressEventArgs(fileSize, 0)); if (!m_EventStopThread.WaitOne(0, true)) { strLocal = new FileStream(fullSavePath + _BeatInfo.BeatType, FileMode.Create, FileAccess.Write, FileShare.None); int bytesSize = 0; byte[] downBuffer = new byte[2048]; while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { if (m_EventStopThread.WaitOne(0, true)) { m_EventThreadStopped.Set(); } else { // write to file strLocal.Write(downBuffer, 0, bytesSize); // update progress bar downloadedSize = strLocal.Length; OnUpdateProgress(new UpdateProgressEventArgs(fileSize, downloadedSize)); } } } } } catch { //m_EventThreadStopped.Set(); //MessageBox.Show(ex.Message); } finally { if (webRequest != null) { webRequest.Abort(); } if (strResponse != null) { strResponse.Close(); } if (strLocal != null) { strLocal.Close(); } if (m_EventThreadStopped.WaitOne(0, true)) { /* try { //File.Delete(fullSavePath + _BeatInfo.BeatType); } catch { } */ OnStopped(); } else { bool hasError = (downloadedSize != fileSize); if (hasError) { OnError(); /* try { //File.Delete(fullSavePath + _BeatInfo.BeatType); } catch { } */ } else { try { if (_BeatInfo.BeatType == ".swf") { MP3.ExtractFromSwf(fullSavePath); } MP3.UpdateInfo(fullSavePath, _BeatInfo); OnCompleted(); } catch { //File.Delete(fullSavePath + ".mp3"); OnError(); } } } } }
public static void CheckUpdate(kIRCCore irc, string irc_target) { Updater = (HttpWebRequest)HttpWebRequest.Create(update_checkerurl); ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; Updater_Response = (HttpWebResponse)Updater.GetResponse(); if (Updater_Response.StatusCode == HttpStatusCode.OK) { irc.Say(irc_target, "kIRC: Contacting updater..."); Stream reads = Updater_Response.GetResponseStream(); byte[] buff = new byte[10]; reads.Read(buff, 0, 10); string ver = Encoding.UTF8.GetString(buff); ver = ver.ToLower().Trim(new[] { ' ', '\r', '\n', '\t' }).TrimEnd(new[] { '\0' }); if (ver == VERSION.ToLower().Trim()) { irc.Say(irc_target, "kIRC: This plugin is using the latest version!"); } else { irc.Say(irc_target, "kIRC Warning: Plugin version mismatch!"); irc.Say(irc_target, "Current version: " + VERSION + ", Latest version on repository is " + ver + "."); } } else { irc.Say(irc_target, "kIRC Error: Failed to contact updater."); } Updater.Abort(); Updater = null; Updater_Response = null; lastchecked = DateTime.Now; }
/// <summary> /// set the notification url /// </summary> /// <param name="sessionId">session id</param> /// <param name="notificationURL">notificaion url</param> /// <returns>true if success else false</returns> public bool SetNotificationInformation(Guid sessionId, string notificationURL) { ISessionManager objSessionMgr = new SessionManager(); try { string connectionGroupName = Guid.NewGuid().ToString(); System.Net.HttpWebRequest lRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(notificationURL); lRequest.ConnectionGroupName = connectionGroupName; ServicePoint servicePoint = lRequest.ServicePoint; try { lRequest.Method = System.Net.WebRequestMethods.Http.Get; using (System.Net.HttpWebResponse lResponse = (System.Net.HttpWebResponse)lRequest.GetResponse()) { if (lResponse.StatusCode == System.Net.HttpStatusCode.OK) { string error = objSessionMgr.SetNotificationURL(sessionId, notificationURL); if (error == string.Empty) { return(true); } else { LogManager.WriteLog(TraceType.ERROR, "Invalid Session Id", "PIS.Ground.Session.SessionService.SetNotificationInformation()", null, EventIdEnum.Session); return(false); } } else { LogManager.WriteLog(TraceType.ERROR, "Invalid Notification URL", "PIS.Ground.Session.SessionService.SetNotificationInformation()", null, EventIdEnum.Session); return(false); } } } finally { if (lRequest != null) { try { lRequest.Abort(); } catch (NotImplementedException) { // Ignore the not implemented exception } } if (servicePoint != null) { servicePoint.CloseConnectionGroup(connectionGroupName); servicePoint = null; } } } catch (Exception ex) { LogManager.WriteLog(TraceType.ERROR, ex.Message, "PIS.Ground.Session.SessionService.SetNotificationInformation()", ex, EventIdEnum.Session); return(false); } }
/// <summary> /// http or https post request /// </summary> /// <param name="requestInput"></param> /// <param name="remoteCertificateValidationCallback"></param> /// <returns></returns> public static string RequestPost(HttpRequestArgs requestInput, Func <object, X509Certificate, X509Chain, SslPolicyErrors, bool> remoteCertificateValidationCallback = null) { var res = string.Empty; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(requestInput.Url); try { request.Method = "POST"; request.ContentType = string.IsNullOrEmpty(requestInput.ContentType) ? "application/x-www-form-urlencoded" : requestInput.ContentType; //application/json; encoding=utf-8 byte[] byte1 = requestInput.GetBodyBytes().Result; request.ContentLength = byte1.Length; if (requestInput.TimeOut > 0) { request.Timeout = requestInput.TimeOut; } if (!requestInput.Host.IsNullOrWhiteSpace()) { request.Host = requestInput.Host; } if (requestInput.Expect100Continue.HasValue) { System.Net.ServicePointManager.Expect100Continue = requestInput.Expect100Continue.Value; } if (requestInput.KeepAlive.HasValue) { request.KeepAlive = requestInput.KeepAlive.Value; } request.ProtocolVersion = requestInput.HttpVer; if (!requestInput.UserAgent.IsNullOrWhiteSpace()) { request.UserAgent = requestInput.UserAgent; } if (requestInput.DefaultConnectionLimit.HasValue) { ServicePointManager.DefaultConnectionLimit = requestInput.DefaultConnectionLimit.Value; } if (requestInput.DnsRefreshTimeout.HasValue) { ServicePointManager.DnsRefreshTimeout = requestInput.DnsRefreshTimeout.Value; } foreach (var header in requestInput.Headers) { request.Headers.Add(header.Key, header.Value); } //验证服务器证书回调自动验证 ServicePointManager.ServerCertificateValidationCallback = ((remoteCertificateValidationCallback == null) ? new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult) : new System.Net.Security.RemoteCertificateValidationCallback(remoteCertificateValidationCallback)); using (Stream newStream = request.GetRequestStream()) { // Send the data. newStream.Write(byte1, 0, byte1.Length); //写入参数 } using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse()) { Encoding coding = string.IsNullOrEmpty(requestInput.CharSet) ? System.Text.Encoding.UTF8 : System.Text.Encoding.GetEncoding(requestInput.CharSet); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), coding)) { var responseMessage = reader.ReadToEnd(); if (response.StatusCode == HttpStatusCode.OK) { res = responseMessage; } response.Close(); } } } catch (Exception ex) { res = string.Format("ERROR:{0}", ex.Message); } finally { request.Abort(); request = null; } return(res); }
private static HttpWebResponse GetRawResponse(HttpWebRequest request) { try { return (HttpWebResponse) request.GetResponse(); } catch (WebException ex) { #if MONODROID // In Android the connections might start to hang (never return // responces) after 3 sequential connection failures (i.e: exceptions) request.Abort(); #endif // Check to see if this is an HTTP error or a transport error. // In cases where an HTTP error occurs ( status code >= 400 ) // return the underlying HTTP response, otherwise assume a // transport exception (ex: connection timeout) and // rethrow the exception if (ex.Response is HttpWebResponse) { return ex.Response as HttpWebResponse; } throw; } }
/// <summary> /// HTTP/HTTPS的GET方法获取HttpWebResponse /// </summary> /// <param name="Url">要GET数据的网址</param> /// <param name="headers">HTTP协议中消息报头所带的headers信息</param> /// <returns>HttpWebResponse</returns> protected void GetResponse(String Url, ref HttpWebResponse Response, ref HttpWebRequest rqst, String[] headers, int level = 0) { //如果使用代理https变为http //if (Url.ToLower().Contains("https://") && proxy.Address != null) // Url = "http" + Url.Substring(5); Uri uri = new Uri(Url); //设置HTTPS方式 if (Url.ToLower().Contains("https://")) ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult; //构造HTTP头 rqst = (HttpWebRequest)WebRequest.Create(uri); rqst.KeepAlive = true; rqst.AllowAutoRedirect = false; rqst.ServicePoint.Expect100Continue = false; rqst.MaximumAutomaticRedirections = 3; rqst.UserAgent = UserAgent; if (reffer != null) { try { rqst.Referer = reffer.AbsoluteUri; } catch { } } foreach (String s in headers) { rqst.Headers.Add(s); } rqst.Timeout = timeOut; rqst.CookieContainer = Cookies; if (proxy.Address != null) { rqst.ProtocolVersion = HttpVersion.Version10; //启用代理 rqst.UseDefaultCredentials = true; rqst.Proxy = proxy; } //记录当前访问页以便下次访问设置Reffer reffer = uri; //访问URL Response = (HttpWebResponse)rqst.GetResponse(); //更新COOKIE foreach (Cookie ck in Response.Cookies) { Cookies.Add(ck); } //防止无限循环跳转 if (level < 10) { //自动重定向网页 if (Response.Headers["Location"] != null) { Response.Close(); rqst.Abort(); String location = Response.Headers["Location"]; if (!location.Contains("://")) location = uri.Scheme + "://" + uri.Authority + location; GetResponse(location, ref Response, ref rqst, ++level); } else if (Response.ResponseUri != uri) { Response.Close(); rqst.Abort(); GetResponse(Response.ResponseUri.AbsoluteUri, ref Response, ref rqst, ++level); } } }
private static void GetResponseAsync(HttpWebRequest request, string method, ref BackgroundWorker bw, ref DoWorkEventArgs e, out string pointer, out string error) { const string SOURCE = CLASS_NAME + "GetResponseAsync"; pointer = ""; error = ""; try { //make async call to get response //then we can abort if Cancel is called on the background worker var state = new RequestState { Request = request, Method = method }; _callbackDone = new ManualResetEvent(false); IAsyncResult ar = request.BeginGetResponse( ResponseCallback, state); //poll every 250 ms const int WAIT = 250; int cycles = 0; ar.AsyncWaitHandle.WaitOne(WAIT, true); while (ar.IsCompleted != true) { cycles += 1; //check for manual/application Cancel if (bw.CancellationPending) { request.Abort(); e.Cancel = true; Logger.Info(SOURCE, string.Format( "aborting request for {0} in response to CancellationPending flag", method)); return; } if (cycles >= 120) { //enforce timeout of 30 seconds (120 * 250ms) request.Abort(); Logger.Info(SOURCE, string.Format( "request for {0} timed out after {1} sec", method, (cycles * WAIT / 1000))); error = "request timed out"; return; } //wait for another 250 ms ar.AsyncWaitHandle.WaitOne(WAIT, true); } _callbackDone.WaitOne(); _callbackDone.Close(); _callbackDone = null; using (var response = state.Response) { if (response != null) { //read the response stream var stream = response.GetResponseStream(); if (stream != null) { using (var reader = new StreamReader(stream)) { var responseText = reader.ReadToEnd(); Logger.Verbose(SOURCE, string.Format("response for {0} = {1}", method, responseText)); switch (method) { case "UpdateContent": error = ParseUpdateResponse(responseText); break; case "ReceiveSegment": error = ParseSegmentResponse(responseText); break; default: ParsePostResponse(responseText, ref pointer, out error); break; } } } } else { //treat this as an error Logger.Warning(SOURCE, string.Format( "no response for {0}", method)); error = "No response"; } } } catch (WebException wex) { //exception will be raised if the server didn't return 200 - OK //try to retrieve more information about the network error if (wex.Response != null) { try { var errResponse = (HttpWebResponse)wex.Response; error = string.Format("code:{0}; desc:{1}", errResponse.StatusCode, errResponse.StatusDescription); } catch (Exception ex) { Logger.Error(SOURCE, ex.ToString()); } } else { error = wex.ToString(); } } catch (Exception ex) { error = ex.ToString(); Logger.Error(SOURCE, ex.ToString()); } }
private void writeRequestBodyFromStream(HttpWebRequest con, Stream data, long streamLength) { // post data Stream s = null; try { con.ContentLength = streamLength; con.SendChunked = false; byte[] buffer = new byte[64 * 1024]; s = con.GetRequestStream(); for (long i = 0; i < streamLength; ) { if (i + buffer.Length > streamLength) { int bytesToRead = (int)(streamLength - i); int count = data.Read(buffer, 0, bytesToRead); if (count == 0) { con.Abort(); throw new EsuException("Premature EOF reading stream at offset " + i); } s.Write(buffer, 0, count); i += count; } else { int count = data.Read(buffer, 0, buffer.Length); if (count == 0) { con.Abort(); throw new EsuException("Premature EOF reading stream at offset " + i); } s.Write(buffer, 0, count); i += count; } } s.Close(); } catch (IOException e) { s.Close(); throw new EsuException("Error posting data", e); } }
/// <summary> /// HTTP文件上传 /// </summary> /// <param name="URL">HTTP上传地址</param> /// <param name="FileFullName">本地文件路径</param> /// <param name="FileName">服务器文件名</param> /// <param name="usesession">是否需要SESSION</param> /// <param name="BufferSize">缓存大小</param> /// <returns>执行结果</returns> public bool UpLoad(string URL, string FileFullName, string FileName = "", bool usesession = false, int BufferSize = 4096) { try { if (URL == null || FileFullName == null) { ErrMsg = "REF unvalid"; return(false); } else if (URL.Trim() == "" || FileFullName.Trim() == "") { ErrMsg = "REF unvalid"; return(false); } else { FileInfo fi = new FileInfo(FileFullName.Trim()); if (fi.Exists) { //时间戳 string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); //请求头部信息 StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(strBoundary); sb.Append("\r\n"); sb.Append("Content-Disposition: form-data; name=\""); sb.Append("file"); sb.Append("\"; filename=\""); if (FileName.Trim() == "") { FileName = fi.Name; } sb.Append(FileName); sb.Append("\""); sb.Append("\r\n"); sb.Append("Content-Type: application/octet-stream"); sb.Append("\r\n"); sb.Append("\r\n"); string strPostHeader = sb.ToString(); byte[] postHeaderBytes; if (CharSet.Trim() != "") { postHeaderBytes = Encoding.GetEncoding(CharSet.Trim()).GetBytes(strPostHeader); } else { postHeaderBytes = Encoding.ASCII.GetBytes(strPostHeader); } myHttpWebRequest = (HttpWebRequest)System.Net.HttpWebRequest.Create(URL); myHttpWebRequest.KeepAlive = keepalive; myHttpWebRequest.Timeout = TOut; if (usesession) { myHttpWebRequest.CookieContainer = session; } if (useragent.Trim() != "") { myHttpWebRequest.UserAgent = useragent; } if (refer.ToString().Trim() != "") { myHttpWebRequest.Referer = refer; } myHttpWebRequest.Method = "POST"; myHttpWebRequest.AllowWriteStreamBuffering = false; myHttpWebRequest.ContentType = "multipart/form-data; boundary=" + strBoundary; long length = fi.Length + postHeaderBytes.Length + boundaryBytes.Length; long fileLength = fi.Length; myHttpWebRequest.ContentLength = length; byte[] buffer = new byte[BufferSize]; int dataRead = 0; using (FileStream fs = fi.OpenRead()) { try { using (Stream rs = myHttpWebRequest.GetRequestStream()) { rs.Write(postHeaderBytes, 0, postHeaderBytes.Length); do { dataRead = fs.Read(buffer, 0, BufferSize); rs.Write(buffer, 0, dataRead); }while (dataRead < BufferSize); } } catch { } finally { fs.Close(); } } myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); iStatCode = (int)myHttpWebResponse.StatusCode; if (iStatCode == 200) { myHttpWebResponse.Close(); myHttpWebRequest.Abort(); return(true); } else { myHttpWebResponse.Close(); myHttpWebRequest.Abort(); ErrMsg = "HTTP ERR:" + iStatCode.ToString(); return(false); } } else { ErrMsg = "File Not Exists"; return(false); } } } catch (Exception ex) { ErrMsg = ex.Message; return(false); } }
private HttpWebResponse GetResponseWithTimeout(HttpWebRequest req) { AutoResetEvent ev=new AutoResetEvent(false); IAsyncResult result =req.BeginGetResponse(GetResponseCallback, ev); if (!ev.WaitOne(ResponseTimeout)) { req.Abort(); return null; } /* if (!HttpClientParams.WaitOneEmpty) { if (!ev.WaitOne(ResponseTimeout)) { req.Abort(); return null; } } else if (!ev.WaitOne()) { req.Abort(); return null; } */ /*if (!m_Ajax) */Referer = req.RequestUri.ToString(); return (HttpWebResponse)req.EndGetResponse(result); }
public RequestTimeout(HttpWebRequest wr_) { wr = wr_; timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 0, 10, 0); timer.Tick += delegate(object s, EventArgs args) { timer.Stop(); if (wr.UserAgent != "dispatched") { wr.UserAgent = "aborted_by_timeout"; wr.Abort(); } }; timer.Start(); }
void CleanupOnError(HttpWebRequest request, HttpWebResponse response) { if (response != null) { response.Close(); } if (request != null) { request.Abort(); } this.Cleanup(); this.RemoveIdentityMapping(true); }
protected byte[] UploadDataCore(Uri address, string method, byte[] data, object userToken) { uploadDataRequest = (HttpWebRequest)SetupRequest(address); // Mono insists that if you have Content-Length set, Keep-Alive must be true. // Otherwise the unhelpful exception of "Content-Length not set" will be thrown. // The Linden Lab event queue server breaks HTTP 1.1 by always replying with a // Connection: Close header, which will confuse the Windows .NET runtime and throw // a "Connection unexpectedly closed" exception. This is our cross-platform hack if (Helpers.GetRunningRuntime() == Helpers.Runtime.Mono) uploadDataRequest.KeepAlive = true; try { // Content-Length int contentLength = data.Length; uploadDataRequest.ContentLength = contentLength; using (Stream stream = uploadDataRequest.GetRequestStream()) { // Most uploads are very small chunks of data, use an optimized path for these if (contentLength < 4096) { stream.Write(data, 0, contentLength); } else { // Upload chunks directly instead of buffering to memory uploadDataRequest.AllowWriteStreamBuffering = false; MemoryStream ms = new MemoryStream(data); byte[] buffer = new byte[checked((uint)Math.Min(4096, (int)contentLength))]; int bytesRead = 0; while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, bytesRead); if (UploadProgressChanged != null) { UploadProgressChanged(this, new UploadProgressChangedEventArgs(0, 0, bytesRead, contentLength, userToken)); } } ms.Close(); } } HttpWebResponse response = null; Exception responseException = null; IAsyncResult result = uploadDataRequest.BeginGetResponse( delegate(IAsyncResult asyncResult) { try { response = (HttpWebResponse)uploadDataRequest.EndGetResponse(asyncResult); } catch (Exception ex) { responseException = ex; } }, null); // Not sure if one of these is better than the other, but // ThreadPool.RegisterWaitForSingleObject fails to wait on Mono 1.9.1 in this case result.AsyncWaitHandle.WaitOne(1000 * 100, false); //ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, // delegate(object state, bool timedOut) { }, null, 1000 * 100, true); if (responseException != null) { // Exception occurred throw responseException; } else if (response == null) { // No exception, but no response throw new WebException("No response from the CAPS server", WebExceptionStatus.ReceiveFailure); } else { // Server responded Stream st = ProcessResponse(response); contentLength = (int)response.ContentLength; return ReadAll(st, contentLength, userToken, true); } } catch (ThreadInterruptedException) { if (uploadDataRequest != null) uploadDataRequest.Abort(); throw; } }
public static void AbortRequest(HttpWebRequest request) { request.Abort(); }
/// <summary> /// Initialization for a ftp remote file (i.e http://). Use HttpWebRequest for checking path. /// Then open a stream and get file size. Use Utility.Crc32 to calculate the CRC on the stream. /// All errors are catch and write in log manager. /// </summary> private void mInitHttpFile() { try { string connectionGroupName = Guid.NewGuid().ToString(); System.Net.HttpWebRequest lRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(_filePath); lRequest.ConnectionGroupName = connectionGroupName; ServicePoint servicePoint = lRequest.ServicePoint; try { lRequest.Method = System.Net.WebRequestMethods.Http.Head; using (System.Net.HttpWebResponse lResponse = (System.Net.HttpWebResponse)lRequest.GetResponse()) { _exists = true; _fileType = FileTypeEnum.HttpFile; //CalculCRC Utility.Crc32 lCrcCalculator = new PIS.Ground.Core.Utility.Crc32(); System.IO.Stream lFileStream; OpenReadHttpFile(out lFileStream, connectionGroupName); if (lFileStream != null) { using (lFileStream) { _size = lFileStream.Length; _crc = lCrcCalculator.CalculateChecksum(lFileStream); } } else { PIS.Ground.Core.LogMgmt.LogManager.WriteLog(PIS.Ground.Core.Data.TraceType.ERROR, "mInitHttpFile returned null file", "PIS.Ground.Core.Data.RemoteFileClass", null, EventIdEnum.GroundCore); } } } finally { if (lRequest != null) { try { lRequest.Abort(); } catch (NotImplementedException) { // Ignore the not implemented exception } } if (servicePoint != null) { servicePoint.CloseConnectionGroup(connectionGroupName); servicePoint = null; } } } catch (NotSupportedException lEx) { PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, "mInitHttpFile() NotSupportedException with FilePath : " + _filePath, "PIS.Ground.Core.Data.RemoteFileClass", lEx, EventIdEnum.GroundCore); } catch (System.Security.SecurityException lEx) { PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, "mInitHttpFile() SecurityException with FilePath : " + _filePath, "PIS.Ground.Core.Data.RemoteFileClass", lEx, EventIdEnum.GroundCore); } catch (UriFormatException lEx) { PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, "mInitHttpFile() UriFormatException with FilePath : " + _filePath, "PIS.Ground.Core.Data.RemoteFileClass", lEx, EventIdEnum.GroundCore); } catch (Exception lEx) { PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, "mInitHttpFile() UnsupportedException with FilePath : " + _filePath, "PIS.Ground.Core.Data.RemoteFileClass", lEx, EventIdEnum.GroundCore); } }
public static bool Pump(Beat type) { string postVars = staticVars; string url = "http://www.minecraft.net/heartbeat.jsp"; int totalTries = 0; retry: try { int hidden = 0; totalTries++; // append additional information as needed switch (type) { case Beat.Minecraft: if (Server.logbeat) { beatlogger = new StreamWriter("heartbeat.log", true); } postVars += "&salt=" + Server.salt; goto default; case Beat.MCPink: if (hash == null) { throw new Exception("Hash not set"); } url = "http://www.mclawl.tk/hbannounce.php"; if (Player.number > 0) { players = ""; foreach (Player p in Player.players) { if (p.hidden) { hidden++; continue; } players += p.name + " (" + p.group.name + ")" + ","; } if (Player.number - hidden > 0) postVars += "&players=" + players.Substring(0, players.Length - 1); } worlds = ""; foreach (Level l in Server.levels) { worlds += l.name + ","; postVars += "&worlds=" + worlds.Substring(0, worlds.Length - 1); } postVars += "&motd=" + UrlEncode(Server.motd) + "&lvlcount=" + (byte)Server.levels.Count + "&lawlversion=" + Server.Version.Replace(".0", "") + "&hash=" + hash; goto default; case Beat.TChalo: if (hash == null) throw new Exception("Hash not set"); url = "http://minecraft.tchalo.com/announce.php"; // build list of current players in server if (Player.number > 0) { players = ""; foreach (Player p in Player.players) { if (p.hidden) { hidden++; continue; } players += p.name + ","; } if (Player.number - hidden > 0) postVars += "&players=" + players.Substring(0, players.Length - 1); } worlds = ""; foreach (Level l in Server.levels) { worlds += l.name + ","; postVars += "&worlds=" + worlds.Substring(0, worlds.Length - 1); } postVars += "&motd=" + UrlEncode(Server.motd) + "&hash=" + hash + "&data=" + Server.Version + "," + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + "&server=MCPink" + "&details=Running MCPink version " + Server.Version; goto default; default: postVars += "&users=" + (Player.number - hidden); break; } request = (HttpWebRequest)WebRequest.Create(new Uri(url)); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); byte[] formData = Encoding.ASCII.GetBytes(postVars); request.ContentLength = formData.Length; request.Timeout = 15000; retryStream: try { using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(formData, 0, formData.Length); if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Request sent at " + DateTime.Now.ToString()); } requestStream.Close(); } } catch (WebException e) { //Server.ErrorLog(e); if (e.Status == WebExceptionStatus.Timeout) { if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Timeout detected at " + DateTime.Now.ToString()); } goto retryStream; //throw new WebException("Failed during request.GetRequestStream()", e.InnerException, e.Status, e.Response); } else if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Non-timeout exception detected: " + e.Message); beatlogger.Write("Stack Trace: " + e.StackTrace); } } //if (hash == null) //{ using (WebResponse response = request.GetResponse()) { using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) { if (hash == null) { string line = responseReader.ReadLine(); if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Response received at " + DateTime.Now.ToString()); beatlogger.WriteLine("Received: " + line); } hash = line.Substring(line.LastIndexOf('=') + 1); serverURL = line; //serverURL = "http://" + serverURL.Substring(serverURL.IndexOf('.') + 1); Server.s.UpdateUrl(serverURL); File.WriteAllText("text/externalurl.txt", serverURL); Server.s.Log("URL found: " + serverURL); } else if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Response received at " + DateTime.Now.ToString()); } } } //} //Server.s.Log(string.Format("Heartbeat: {0}", type)); } catch (WebException e) { if (e.Status == WebExceptionStatus.Timeout) { if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Timeout detected at " + DateTime.Now.ToString()); } Pump(type); } } catch { if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Heartbeat failure #" + totalTries + " at " + DateTime.Now.ToString()); } if (totalTries < 3) goto retry; if (type == Beat.Minecraft && Server.logbeat) { beatlogger.WriteLine("Failed three times. Stopping."); beatlogger.Close(); } return false; } finally { request.Abort(); } if (beatlogger != null) { beatlogger.Close(); } return true; }
private static void get(HttpWebRequest request, YebobHandler handler, ErrorHandler onError) { request.AllowReadStreamBuffering = true; var ob = Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse); if(onError == null){ onError = new ErrorHandler(defaultErrorHandler); } Log.d("Yebob send " + DateTime.Now); Observable.Timeout(ob.Invoke(), DateTimeOffset.Now.AddSeconds(10)) .ObserveOnDispatcher() //include if UI accessed from subscribe .Subscribe(response => { Log.d("Yebob recv " + DateTime.Now); using (var responseStream = response.GetResponseStream()) { using (var sr = new StreamReader(responseStream, Encoding.UTF8)) { String result = sr.ReadToEnd(); handleResponse(result, handler, onError); } } }, ex => { Log.e("Yebob error " + ex.Message); onError(ERROR.HTTP_HAS_EXCEPTION, "Yebob error " + ex.Message); request.Abort(); }); }
private HttpWebResponse GetResponseWithTimeout(HttpWebRequest req) { bool m_Ajax = Ajax; Ajax = false; AutoResetEvent ev=new AutoResetEvent(false); IAsyncResult Japan =req.BeginGetResponse(GetResponseCallback, ev); if(!ev.WaitOne(Timeout)) { req.Abort(); return null; } if (!m_Ajax) Referer = req.RequestUri.ToString(); return (HttpWebResponse)req.EndGetResponse(Japan); }
private void learn360Test() { string eBookLink = "https://learn360.infobase.com/PortalPlaylists.aspx?wID=266625&xtid=96801"; string downloadAddress = string.Empty; string baseNewLearn360Link = NewLearn360Link(eBookLink); if (!string.IsNullOrEmpty(baseNewLearn360Link) && eBookLink.Contains("xtid=")) { string videoID = eBookLink.Substring(eBookLink.IndexOf("xtid=") + "xtid=".Length); if (videoID.IndexOf("&") == 0) { videoID = null; } else if (videoID.IndexOf("&") > 0) { videoID = videoID.Substring(0, videoID.IndexOf("&")); } if (!string.IsNullOrWhiteSpace(videoID)) { downloadAddress = baseNewLearn360Link.ToLower(); if (downloadAddress.Contains("portalplaylists.aspx?")) { downloadAddress = baseNewLearn360Link.Replace(baseNewLearn360Link.Substring(downloadAddress.IndexOf("portalplaylists.aspx?")), ""); } else { downloadAddress = baseNewLearn360Link; } downloadAddress += "image/" + videoID; } } if (!string.IsNullOrWhiteSpace(downloadAddress)) { //string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "~imageCT" + itemID + ".JPG"; //alivya add contentType check logic at 2017-07-28, ver 8.1.4. bool isImageContent = false; System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(downloadAddress); System.Net.WebResponse webResponse = httpWebRequest.GetResponse(); if (webResponse.ContentType.ToLower().StartsWith("image")) { isImageContent = true; } httpWebRequest.Abort(); webResponse.Close(); string fileName = "~imageCT2269399.JPG"; if (isImageContent) { System.Net.WebClient webClient = new System.Net.WebClient(); webClient.DownloadFile(downloadAddress, fileName); FileInfo info = new FileInfo(fileName); if (info.Exists) { if (info.Length > 1000) { FileStream stream = new FileStream(fileName, FileMode.Open); int length = (int)stream.Length; byte[] buffer = new byte[length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); } } } } }