internal WebRequest(System.Net.WebRequest webRequest) { if (webRequest == null) throw new ArgumentNullException("webRequest"); _webRequest = webRequest; }
/// <summary> /// Constructor /// </summary> /// <param name="request">The request reported through this event</param> /// <param name="requestHeaders">The request header collection.</param> internal SendingRequestEventArgs(System.Net.WebRequest request, System.Net.WebHeaderCollection requestHeaders) { // In Silverlight the request object is not accesible Debug.Assert(null != request, "null request"); Debug.Assert(null != requestHeaders, "null requestHeaders"); this.request = request; this.requestHeaders = requestHeaders; }
internal SendingRequestEventArgs(System.Net.WebRequest request, System.Net.WebHeaderCollection requestHeaders) { #if ASTORIA_LIGHT Debug.Assert(null == request, "non-null request in SL."); #else Debug.Assert(null != request, "null request"); #endif Debug.Assert(null != requestHeaders, "null requestHeaders"); this.request = request; this.requestHeaders = requestHeaders; }
/// <summary> /// Constructor /// </summary> /// <param name="request">The request reported through this event</param> /// <param name="requestHeaders">The request header collection.</param> internal SendingRequestEventArgs(System.Net.WebRequest request, System.Net.WebHeaderCollection requestHeaders) { // In Silverlight the request object is not accesible #if ASTORIA_LIGHT Debug.Assert(null == request, "non-null request in SL."); #else Debug.Assert(null != request, "null request"); #endif Debug.Assert(null != requestHeaders, "null requestHeaders"); this.request = request; this.requestHeaders = requestHeaders; }
protected void Start_Clicked(object sender, EventArgs e) { ProgressLabel.Text = "Page_Load: thread #" + System.Threading.Thread.CurrentThread.GetHashCode(); BeginEventHandler bh = new BeginEventHandler(this.BeginGetAsyncData); EndEventHandler eh = new EndEventHandler(this.EndGetAsyncData); AddOnPreRenderCompleteAsync(bh, eh); // Initialize the WebRequest. string address = "http://localhost/"; myRequest = System.Net.WebRequest.Create(address); }
public static string Getip() //判断是否联网 { string strUrl = "http://www.ip138.com/ip2city.asp"; //获得IP的网址了 Uri uri = new Uri(strUrl); System.Net.WebRequest wr = System.Net.WebRequest.Create(uri); System.IO.Stream s = wr.GetResponse().GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(s, Encoding.Default); string all = sr.ReadToEnd(); //读取网站的数据 int i = all.IndexOf("[") + 1; string tempip = all.Substring(i, 15); string ip = tempip.Replace("]", "").Replace(" ", "");//找出i return(ip); }
bool testaConexao(string site) { System.Net.WebRequest requisita = System.Net.WebRequest.Create(site); try { System.Net.WebResponse respo = requisita.GetResponse(); respo.Close(); requisita = null; return(true); } catch { requisita = null; //manda msg return(false); } }
/// <summary> /// http://blogs.msdn.com/b/translation/p/gettingstarted2.aspx /// </summary> private static void sample_usage() { //1. string clientID = "NotiQ1"; string clientSecret = "lrOB6czlivrqK91fc2XmeRgDTrqf7mwO/NogL6OtNro="; String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret)); System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails); webRequest.ContentLength = bytes.Length; using (System.IO.Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } System.Net.WebResponse webResponse = webRequest.GetResponse(); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); //Get deserialized object from JSON stream AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); string headerValue = "Bearer " + token.access_token; //2. string txtToTranslate = "awesome"; string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=pl"; System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri); translationWebRequest.Headers.Add("Authorization", headerValue); System.Net.WebResponse response = translationWebRequest.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode); string responseStr = translatedStream.ReadToEnd(); System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument(); xTranslation.LoadXml(responseStr); string translatedText = xTranslation.InnerText; }
private void GetPublicIPAddress(object sender, DoWorkEventArgs e) { try { string sURL = "http://icanhazip.com"; System.Net.WebRequest wrGETURL = System.Net.WebRequest.Create(sURL); Stream objStream = wrGETURL.GetResponse().GetResponseStream(); StreamReader objReader = new StreamReader(objStream); e.Result = objReader.ReadLine(); } catch (Exception /*ex*/) { e.Result = "Not available"; } }
public string GetPageHTML(string pageUrl, int timeoutSeconds) { System.Net.WebResponse response = null; try { // Setup our Web request System.Net.WebRequest request = System.Net.WebRequest.Create(pageUrl); HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); request.CachePolicy = noCachePolicy; try { request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } catch (Exception proxyE) { PumpString("Error setting proxy server: " + proxyE.Message, false, false, new Version(), false, ""); } request.Timeout = timeoutSeconds * 1000; // Retrieve data from request response = request.GetResponse(); System.IO.Stream streamReceive = response.GetResponseStream(); System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("utf-8"); System.IO.StreamReader streamRead = new System.IO.StreamReader(streamReceive, encoding); // return the retrieved HTML return(streamRead.ReadToEnd()); } catch (Exception ex) { // Error occured grabbing data, return empty string. PumpString("An error occurred while retrieving the HTML content. " + ex.Message, false, false, new Version(), false, ""); return(""); } finally { // Check if exists, then close the response. if (response != null) { response.Close(); } } }
public static long GetFileSize(string url) { Console.WriteLine(url); long result = -1; System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "HEAD"; using (System.Net.WebResponse resp = req.GetResponse()) { if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength)) { result = ContentLength; } } return(result); }
public List <Currency> ReadHtmlSite(string address) { List <Currency> courrencyList = new List <Currency>(); System.Net.WebRequest req = System.Net.WebRequest.Create(address); System.Net.WebResponse resp = req.GetResponse(); System.IO.Stream stream = resp.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(stream); string s = sr.ReadToEnd(); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(s); if (doc != null) { HtmlNodeCollection tables = doc.DocumentNode.SelectNodes(@"/table"); HtmlNodeCollection tablerows = null; for (int i = 0; i < tables.Count; ++i) { if (tables[i].Id == "DataGrid1") { tablerows = tables[i].SelectNodes(@".tr"); } } for (int i = 1; i < tablerows.Count; ++i) { HtmlNodeCollection tablecolumns = tablerows[i].SelectNodes(@"./td"); string DC = tablecolumns[0].InnerText; string LC = tablecolumns[1].InnerText; string NU = tablecolumns[2].InnerText; string CurrencyName = tablecolumns[3].InnerText; string CurrencyCource = tablecolumns[4].InnerText; Currency tmp = new Currency(); tmp.DigitalCode = DC; tmp.LetterCode = LC; tmp.NumberUnit = System.Convert.ToInt32(NU); tmp.Name = CurrencyName; tmp.Number = System.Convert.ToDouble(CurrencyCource.Replace('.', ',')); courrencyList.Add(tmp); } } return(courrencyList); }
///// <summary> ///// 取得上证指数 ///// </summary> //public string GetStkXML() //{ // string obj = ""; // string url = "http://wap.tzt.cn"; // HttpRequestCache httpRequest = new HttpRequestCache(url); // httpRequest.Fc.CacheUsed = this._CacheUsed; // httpRequest.Fc.CacheTime = this._CacheTime; // httpRequest.Fc.CacheFolder = this._CacheFolder; // httpRequest.Fc.CacheFile = "上证指数"; // httpRequest.WebAsync.RevCharset = "UTF-8"; // if (httpRequest.MethodGetUrl(out this._ResponseValue)) // obj = StkHtml(this._ResponseValue); // return obj; //} ///// <summary> ///// 处理详细上证指数 ///// </summary> ///// <param name="p_html">HTML文档</param> //private string StkHtml(string p_html) //{ // return p_html; // //if (string.IsNullOrEmpty(p_html)) // // return ""; // //string pattern = @"<strong>沪\:([\s\S]+?)<strong>深\:"; // //Match m1 = Regex.Match(p_html, pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); // //if (m1.Success) // //{ // // string str = m1.Groups[1].Value.Replace("</strong><br/>", ""); // // return str; // //} // //else // // return ""; //} /// <summary> /// 抓取一个网页源码 /// </summary> /// <param name="url"></param> /// <returns></returns> private string GetSourceTextByUrl(string url, string Encoding) { try { System.Net.WebRequest request = System.Net.WebRequest.Create(url); request.Timeout = 20000; System.Net.WebResponse response = request.GetResponse(); System.IO.Stream resStream = response.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(resStream, System.Text.Encoding.GetEncoding(Encoding)); return(sr.ReadToEnd()); } catch { return(""); } }
public static string URLResponding(string url) { //Log.doLog("Sjekker url: " + url); try { System.Net.WebRequest req = System.Net.WebRequest.Create(url); System.Net.WebResponse res = req.GetResponse(); res.Close(); return(null); } catch (System.Net.WebException ex) { //Console.WriteLine(ex.Message); return(ex.Message); } }
public static string httpGet(string address) { string textResponse = string.Empty; try { System.Net.WebRequest request = System.Net.WebRequest.Create(address); System.Net.WebResponse response = request.GetResponse(); System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream()); textResponse = streamReader.ReadToEnd(); } catch (Exception ex) { ErrorHandler.errorRaised(ex); } return(textResponse); }
public void POST_Traid(string instr, string categories) { /*NameValueCollection Investing; * Investing = ConfigurationManager.GetSection("appSettings_API_Libertex") as NameValueCollection; * string url = Investing.Get("API"); * * Investing = ConfigurationManager.GetSection(categories) as NameValueCollection; * * string url_ref = Investing.Get(instr); * url_ref = Regex.Replace(url_ref, "https://app.libertex.org/products/", ""); * url_ref = Regex.Replace(url_ref, "agriculture/", ""); * url_ref = Regex.Replace(url_ref, "currency/", ""); * url_ref = Regex.Replace(url_ref, "crypto/", ""); * url_ref = Regex.Replace(url_ref, "indexes/", ""); * url_ref = Regex.Replace(url_ref, "energetics/", ""); * url_ref = Regex.Replace(url_ref, "metal/", ""); * url_ref = Regex.Replace(url_ref, "stock/", ""); * url_ref = Regex.Replace(url_ref, "etf/", ""); * url_ref = Regex.Replace(url_ref, "/", ""); * MessageBox.Show(url_ref);*/ string ProxyString = ""; string URI = @"https://app.libertex.org/spa/investing/open-position";; string Parameters = "symbol=USDSEK&sumInv=50&mult=5&direction=reduction&number=12318195401&rate=9.275139999999999&spread=0.0038299999999999996&time=1561731033000" + "&isAutoIncreaseEnabled=0&csrfToken=3f1e3d4953a0dafce50d9df780002c55-99a786c105f3ce28216311484c8e45aa"; System.Net.WebRequest req = System.Net.WebRequest.Create(URI); //req.Proxy = new System.Net.WebProxy(ProxyString, true); req.ContentType = "application/json"; req.Method = "POST"; //byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Parameters); req.ContentLength = bytes.Length; System.IO.Stream os = req.GetRequestStream(); // создаем поток os.Write(bytes, 0, bytes.Length); // отправляем в сокет os.Close(); System.Net.WebResponse resp = req.GetResponse(); if (resp == null) { MessageBox.Show("Что то ответ пустой"); return; } System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); MessageBox.Show(sr.ReadToEnd().Trim()); }
public async System.Threading.Tasks.Task <IEnumerable <session_response> > Get() { try { string request_string = Program.config_couchdb_url + "/session"; System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string)); request.PreAuthenticate = false; System.Net.WebResponse response = await request.GetResponseAsync(); System.IO.Stream dataStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); session_response json_result = Newtonsoft.Json.JsonConvert.DeserializeObject <session_response>(responseFromServer); if (response.Headers["Set-Cookie"] != null) { this.Response.Headers.Add("Set-Cookie", response.Headers["Set-Cookie"]); string[] set_cookie = response.Headers["Set-Cookie"].Split(';'); string[] auth_array = set_cookie[0].Split('='); if (auth_array.Length > 1) { string auth_session_token = auth_array[1]; json_result.auth_session = auth_session_token; } else { json_result.auth_session = ""; } } session_response[] result = new session_response[] { json_result }; return(result); } catch (Exception ex) { Console.WriteLine(ex); } return(null); }
// This function must be called by the client application to initiate retrieval. public void Start() { if (this.state == RetrieverState.NotReady) { throw new RetrieverStateException( "Retriever requires the URI to be set before calling Start()."); } if (this.state == RetrieverState.Retrieving) { throw new RetrieverStateException("Retrieval already in progress."); } try { this.startTime = System.DateTime.Now; this.previousProgressTime = this.startTime; this.webRequest = System.Net.WebRequest.Create(this.request.Uri); // Handle any proxy the system may have defined. System.Net.WebProxy proxy = System.Net.WebProxy.GetDefaultProxy(); if (proxy.Address != null) { this.webRequest.Proxy = proxy; } this.webRequest.BeginGetResponse( new System.AsyncCallback(this.onRetrieval), this); // Compute an interval to check on progress, but make sure it's // at least some reasonable minimum: say, 10 milliseconds. ulong monitorInterval = (ulong)System.Math.Min( this.timeoutInterval.Milliseconds, this.progressInterval.Milliseconds); this.monitor.Interval = (int)System.Math.Max(monitorInterval, 10); this.monitor.Start(); this.canceled = false; this.state = RetrieverState.Retrieving; } catch (System.Exception e) { throw e; } }
private IWebRequest Wrap(System.Net.WebRequest webRequest) { if (webRequest is System.Net.FileWebRequest) { return(new FileWebRequest(webRequest as System.Net.FileWebRequest)); } if (webRequest is System.Net.FtpWebRequest) { return(new FtpWebRequest(webRequest as System.Net.FtpWebRequest)); } if (webRequest is System.Net.HttpWebRequest) { return(new HttpWebRequest(webRequest as System.Net.HttpWebRequest)); } throw new NotSupportedException("Unsupported web request type: " + webRequest.GetType()); }
/// <summary> /// 获取HTML源码信息(Porschev) /// </summary> /// <param name="url">获取地址</param> /// <returns>HTML源码</returns> static string GetHtml(string url) { string str = ""; try { Uri uri = new Uri(url); System.Net.WebRequest wr = System.Net.WebRequest.Create(uri); System.IO.Stream s = wr.GetResponse().GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(s, Encoding.Default); str = sr.ReadToEnd(); } catch (Exception e) { } return(str); }
static StackObject *set_ContentLength_3(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *ptr_of_this_method; StackObject *__ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int64 @value = *(long *)&ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Net.WebRequest instance_of_this_method = (System.Net.WebRequest) typeof(System.Net.WebRequest).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.ContentLength = value; return(__ret); }
/// <summary> /// 获取链接返回数据 /// </summary> /// <param name="Url">链接</param> /// <param name="type">请求类型</param> /// <returns></returns> public string GetUrltoHtml(string Url, string type) { try { System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { return(reader.ReadToEnd()); } } catch (System.Exception ex) { return(ex.Message); } }
public bool VerifyConnectionURL(string mURL) { try { System.Net.WebRequest Peticion = System.Net.WebRequest.Create(mURL); System.Net.WebResponse Respuesta = Peticion.GetResponse(); return(true); } catch (System.Net.WebException ex) { if (ex.Status == System.Net.WebExceptionStatus.NameResolutionFailure) { return(false); } return(false); } }
private TokenResponse AcquireAccessToken(string PostBody, string EndPointUrl) { TokenResponse result = null; System.Net.WebRequest request = System.Net.WebRequest.Create(EndPointUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; try { using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(PostBody); streamWriter.Flush(); streamWriter.Close(); } System.Net.WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.Default); string jsonResponse = reader.ReadToEnd(); // Deserialize and get an Access Token. result = Deserialize <TokenResponse>(jsonResponse); } } catch (System.Net.WebException ex) { System.Net.WebResponse response = ex.Response; using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.Default); string jsonResponse = reader.ReadToEnd(); MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace + "\r\n\r\n" + jsonResponse, "Office365APIEditor"); } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, "Office365APIEditor"); } return(result); }
public static bool IsInternetConnection() { System.Net.WebRequest req = System.Net.WebRequest.Create("https://www.google.de/"); System.Net.WebResponse resp; try { resp = req.GetResponse(); resp.Close(); req = null; return(true); } catch (Exception ex) { req = null; return(false); } }
private String[,] getRssData(String channel) { System.Net.WebRequest myRequest = System.Net.WebRequest.Create(channel); System.Net.WebResponse myResponse = myRequest.GetResponse(); System.IO.Stream rssStream = myResponse.GetResponseStream(); System.Xml.XmlDocument rssDoc = new System.Xml.XmlDocument(); rssDoc.Load(rssStream); System.Xml.XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item"); String[,] tempRssData = new String[rssItems.Count, 3]; for (int i = 0; i < rssItems.Count; i++) { System.Xml.XmlNode rssNode; rssNode = rssItems.Item(i).SelectSingleNode("title"); if (rssNode != null) { tempRssData[i, 0] = rssNode.InnerText; } else { tempRssData[i, 0] = ""; } rssNode = rssItems.Item(i).SelectSingleNode("description"); if (rssNode != null) { tempRssData[i, 1] = rssNode.InnerText; } else { tempRssData[i, 1] = ""; } rssNode = rssItems.Item(i).SelectSingleNode("link"); if (rssNode != null) { tempRssData[i, 2] = rssNode.InnerText; } else { tempRssData[i, 2] = ""; } } return(tempRssData); }
//Copy pasted from stackoverflow (see sources) //Gets the public IP for the current computer public static string GetPublicIP() { string url = "http://checkip.dyndns.org"; System.Net.WebRequest req = System.Net.WebRequest.Create(url); System.Net.WebResponse resp = req.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); string response = sr.ReadToEnd().Trim(); string[] a = response.Split(':'); string a2 = a[1].Substring(1); string[] a3 = a2.Split('<'); string a4 = a3[0]; return(a4); }
public Stream DownLoad1(Uri uri) { try { System.Net.WebRequest wReq = System.Net.WebRequest.Create(uri); // Get the response instance. System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) return(respStream); } catch (System.Exception ex) { //errorMsg = ex.Message; } return(null); }
public static void GetPictures(string url, string destFilename) { try { System.Net.WebRequest webreq = System.Net.WebRequest.Create(url); System.Net.WebResponse webres = webreq.GetResponse(); using (System.IO.Stream stream = webres.GetResponseStream()) { Image img = Image.FromStream(stream); img.Save(destFilename); //img.Dispose(); } } catch (Exception ex) { } }
/// <summary> /// Подключение объекта класса по интерфейсу из DLL по URL /// Конструктор класса должен быть без аргументов /// (Используется для интерфейсов) /// </summary> /// <param name="url">Ссылка</param> /// <returns>Объект класса</returns> public static T LoadFromDLL_URL(string url) { System.Net.WebRequest wr = System.Net.HttpWebRequest.Create(url); wr.Method = "GET"; wr.Timeout = 30000; System.Net.WebResponse rp = wr.GetResponse(); System.IO.Stream ss = rp.GetResponseStream(); string dd = System.Environment.SpecialFolder.ApplicationData.ToString() + @"\#tmplda\"; if (!System.IO.Directory.Exists(dd)) { System.IO.Directory.CreateDirectory(dd); } string f = DateTime.UtcNow.Ticks.ToString(); f = f.Substring(f.Length - 7); string ff = dd + f + ".dll"; System.IO.FileStream fs = new FileStream(ff, FileMode.CreateNew); int rb = -1; while ((rb = ss.ReadByte()) >= 0) { fs.WriteByte((byte)rb); } ss.Close(); fs.Close(); rp.Close(); System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFile(ff); Type[] tps = asm.GetTypes(); Type asmType = null; foreach (Type tp in tps) { if (tp.GetInterface(typeof(T).ToString()) != null) { asmType = tp; } } System.Reflection.ConstructorInfo ci = asmType.GetConstructor(new Type[] { }); return((T)ci.Invoke(new object[] { })); }
private bool DownloadWorker2(string url, string imageName, int imageSize) { byte[] buf = new byte[2048]; int n = 0; _LastException = null; System.Net.WebRequest req = System.Net.WebRequest.Create(url); MarkNoCache(req); System.Net.WebResponse resp = req.GetResponse(); var action = new Action <ProgressBar, int>((p, v) => p.Value = v); cancelAction = false; using (Stream s1 = new FileStream(imageName, FileMode.CreateNew)) { using (Stream s2 = resp.GetResponseStream()) { do { n = s2.Read(buf, 0, buf.Length); // delay, so that the progress bar is visible even for relatively small downloads. if (imageSize < 20000) { System.Threading.Thread.Sleep(250); } else if (imageSize < 40000) { System.Threading.Thread.Sleep(100); } else if (imageSize < 100000) { System.Threading.Thread.Sleep(50); } else if (imageSize < 250000) { System.Threading.Thread.Sleep(20); } totalBytesTransferred += n; if (n > 0) { s1.Write(buf, 0, n); } pbDownload.Dispatcher.Invoke(action, pbDownload, totalBytesTransferred); } while (n > 0 && !cancelAction); } } return(!cancelAction); }
/// <summary> /// 取得User Name, Email /// </summary> private async Task <(CloudStorageResult result, string userName, string userEmail)> GetUserInfoAsync() { string userName = null, userEmail = null; CloudStorageResult result = new CloudStorageResult(); try { System.Net.WebRequest request = System.Net.WebRequest.Create(UerInfoEndpoint + oauthClient.AccessToken); request.Method = "GET"; request.ContentType = "application/json"; // Get the response. System.Net.WebResponse response = await request.GetResponseAsync(); // Display the status. //Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = await reader.ReadToEndAsync(); // Display the content. Console.WriteLine(responseFromServer); // Clean up the streams and the response. reader.Close(); reader.Dispose(); dataStream.Close(); dataStream.Dispose(); response.Close(); response.Dispose(); if (!string.IsNullOrEmpty(responseFromServer)) { Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(responseFromServer); userEmail = jObject["email"]?.ToString(); userName = jObject["name"]?.ToString(); result.Status = Status.Success; } } catch (Exception ex) { result.Message = ex.Message; } return(result, userName, userEmail); }
/// <summary> /// Helper function that invokes a thread and the GetRequestStream() or GetResponse() method /// </summary> /// <param name="req">The request to invoke the method on</param> /// <param name="getRequest">A value indicating if the invoked method should be GetRequestStream() or GetResponse()</param> /// <returns>Either a System.IO.Stream or a System.Net.WebResponse object</returns> private static object SafeGetRequestOrResponseStream(System.Net.WebRequest req, bool getRequest) { object[] args = new object[] { req, getRequest, null }; System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(RunSafeGetRequest)); try { //We use the timeout to determine how long we should wait int waitTime = req.Timeout == System.Threading.Timeout.Infinite ? DEFAULT_RESPONSE_TIMEOUT : req.Timeout; t.Start(args); if (t.Join(waitTime)) { if (args[2] == null) { throw new Exception(string.Format("UnexpectedRequestResultError", "null", "")); } else if (args[2] is Exception) { throw (Exception)args[2]; } if (getRequest && args[2] is System.IO.Stream) { return((System.IO.Stream)args[2]); } else if (!getRequest && args[2] is System.Net.WebResponse) { return((System.Net.WebResponse)args[2]); } throw new Exception(string.Format("UnexpectedRequestResultError", args[2].GetType(), args[2].ToString())); } else { t.Abort(); throw new System.Net.WebException("TimeoutException", null, System.Net.WebExceptionStatus.Timeout, null); } } catch { try { t.Abort(); } catch { } throw; } }
private TokenResponse AcquireAccessTokenOfV2WebApp(string AuthorizationCode) { TokenResponse result = null; string accessToken = ""; // Build a POST body. string postBody = "grant_type=authorization_code" + "&redirect_uri=" + System.Web.HttpUtility.UrlEncode(textBox_V2WebAppRedirectUri.Text) + "&client_id=" + textBox_V2WebAppClientID.Text + "&client_secret=" + System.Web.HttpUtility.UrlEncode(textBox_V2WebAppClientSecret.Text) + "&code=" + AuthorizationCode + "&scope=" + textBox_V2WebAppScopes.Text; System.Net.WebRequest request = System.Net.WebRequest.Create("https://login.microsoftonline.com/common/oauth2/v2.0/token"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; try { using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(postBody); streamWriter.Flush(); streamWriter.Close(); } System.Net.WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.Default); string jsonResponse = reader.ReadToEnd(); // Deserialize and get an Access Token. result = Deserialize <TokenResponse>(jsonResponse); accessToken = result.access_token; } } catch (Exception ex) { MessageBox.Show(ex.Message + "\r\n\r\n" + ex.StackTrace, "Office365APIEditor"); } return(result); }
/// <summary> /// 判断是否需要更新 /// </summary> /// <returns></returns> public static bool NeedUpdate(out bool hasError) { string content = string.Empty; hasError = false; try { System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(SystemInstance.UpUrl + "AutoUpdate.ashx")); System.Net.WebResponse response = request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); content = reader.ReadToEnd(); stream.Flush(); reader.Close(); stream.Close(); XmlDocument doc = new XmlDocument(); doc.LoadXml(content); string serverVision = doc.SelectSingleNode("AutoUpdate/UpDate").InnerText.Trim(); if (!String.IsNullOrEmpty(serverVision) && !String.IsNullOrEmpty(SystemInstance.UpDate)) { if (DateTime.Compare(Convert.ToDateTime(serverVision, CultureInfo.InvariantCulture), Convert.ToDateTime(SystemInstance.UpDate, CultureInfo.InvariantCulture)) > 0) { return(true); } } } catch { hasError = true; } return(false); }
void Page_Load(object sender, EventArgs e) { m_TaskIds = new Queue<int>(); m_AsyncResults = new Dictionary<int, IAsyncResult>(); m_AsyncCallbacks = new Dictionary<int, AsyncCallback>(); if (!IsPostBack) { m_MessageQ = new Queue<string>(); Session["ObserverNotified"] = new Queue<string>();//Cross-process? Session["ObserverNotified-Stacked"] = new Stack<string>();//Cross-process? Session["TotalJobQueue"] = new Queue<string>(); Session["countMaxNotification"] = 0; Session["countMaxNotifications"] = 0; Session["TaskQ-Empty"] = true; //init } if (IsAsync) { m_Subject = new SubjectImpl(); m_Subject.Message = new TextBox(); m_Observer = new Observer(m_Subject); // Create an instance of the test class. m_Producer = new AsyncDemo(HttpContext.Current.Session, HttpContext.Current.Trace); m_Producer.NotifyLogger += m_Observer.UpdateLog; m_Producer.AsyncNotificationEvent += ObserverNotified; m_Producer.Attach(); Label1.Text = "Page_Load: thread #" + System.Threading.Thread.CurrentThread.GetHashCode(); BeginEventHandler bh = new BeginEventHandler(this.BeginGetAsyncData); EndEventHandler eh = new EndEventHandler(this.EndGetAsyncData); AddOnPreRenderCompleteAsync(bh, eh); // Initialize the WebRequest. string address = "http://localhost/"; m_MyRequest = System.Net.WebRequest.Create(address); } }
public void Run(bool testRun) { if (!(IsValid && ((parent as Document.Target).IsValid))) throw new InvalidOperationException("Only valid tests on valid targets can be run."); Target target = parent as Target; if (target == null) throw new ApplicationException("Internal Error: unable to access target for this test."); if (relativePath == null) relativePath = ""; string targetPath = target.Path.TrimEnd('/'); string fullPath = targetPath + "/" + relativePath.TrimStart('/'); string paramString = ""; foreach (TestParameter p in parameters) { if (paramString != "") paramString += "&"; paramString += System.Web.HttpUtility.UrlEncode(p.Name); if (!string.IsNullOrEmpty(p.Value)) paramString += "=" + System.Web.HttpUtility.UrlEncode(p.Value); } request = null; System.Net.HttpWebResponse response = null; int responseStatusCode = int.MinValue; string responseBody = null; try { if (!testRun) { Status = TestStatusType.Executing; StatusMessage = "Test is now executing."; } switch (method) { case MethodType.GET: if (paramString != "") fullPath += "?" + paramString; request = System.Net.WebRequest.Create(fullPath); request.Method = "GET"; break; case MethodType.POST: request = System.Net.WebRequest.Create(fullPath); request.ContentType = "application/x-www-form-urlencoded"; request.Method = "POST"; byte[] paramBytes = System.Text.Encoding.ASCII.GetBytes(paramString); request.ContentLength = paramBytes.Length; request.GetRequestStream().Write(paramBytes, 0, paramBytes.Length); break; } response = (System.Net.HttpWebResponse) request.GetResponse(); responseStatusCode = (int)response.StatusCode; System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()); responseBody = sr.ReadToEnd(); if (!testRun) { Status = TestStatusType.Succeeded; StatusMessage = "Test executed successfully."; } } catch (System.Net.WebException wex) { if (wex.Response != null) { System.Net.HttpWebResponse wr = (System.Net.HttpWebResponse)wex.Response; responseStatusCode = (int)wr.StatusCode; } if (!testRun) { if (wex.Status == System.Net.WebExceptionStatus.RequestCanceled) { Status = TestStatusType.Cancelled; StatusMessage = "User cancelled."; } else { Status = TestStatusType.Failed; StatusMessage = wex.Message; } } if (testRun) throw; } catch (Exception ex) { if (!testRun) { Status = TestStatusType.Failed; StatusMessage = ex.Message; } if (testRun) throw; } finally { this.responseStatusCode = responseStatusCode; this.responseBody = responseBody; foreach (Document.Alert alert in alerts) { ICondition condition = alert.Condition as ICondition; condition.SetResponseBody(responseBody); condition.SetResponseStatusCode(responseStatusCode); } } }