public string Create(string url) { try { // setup web request to tinyurl request = (HttpWebRequest)WebRequest.Create(string.Format(TINYURL_ADDRESS_TEMPLATE, url)); request.Timeout = REQUEST_TIMEOUT; request.UserAgent = USER_AGENT; // get response response = (HttpWebResponse)request.GetResponse(); // prase response stream to string Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(ENCODING_NAME)); // convert the buffer into string and store in content StringBuilder sb = new StringBuilder(); while (reader.Peek() >= 0) { sb.Append(reader.ReadLine()); } return sb.ToString(); } catch (Exception) { return null; } }
/// <summary> /// Relays an HttpWebResponse as verbatim as possible. /// </summary> /// <param name="responseToRelay">The HTTP response to relay.</param> public HttpWebResponseResult(HttpWebResponse responseToRelay) { if (responseToRelay == null) { throw new ArgumentNullException("response"); } _response = responseToRelay; Stream contentStream; if (responseToRelay.ContentEncoding.Contains("gzip")) { contentStream = new GZipStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress); } else if (responseToRelay.ContentEncoding.Contains("deflate")) { contentStream = new DeflateStream(responseToRelay.GetResponseStream(), CompressionMode.Decompress); } else { contentStream = responseToRelay.GetResponseStream(); } if (string.IsNullOrEmpty(responseToRelay.CharacterSet)) { // File result _innerResult = new FileStreamResult(contentStream, responseToRelay.ContentType); } else { // Text result var contentResult = new ContentResult(); contentResult = new ContentResult(); contentResult.Content = new StreamReader(contentStream).ReadToEnd(); _innerResult = contentResult; } }
private static string GetResponseBody(HttpWebResponse response) { string responseBody = string.Empty; if (response.ContentEncoding.ToLower().Contains("gzip")) { using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)) { using (StreamReader reader = new StreamReader(stream)) { responseBody = reader.ReadToEnd(); } } } else if (response.ContentEncoding.ToLower().Contains("deflate")) { using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress)) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { responseBody = reader.ReadToEnd(); } } } else { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { responseBody = reader.ReadToEnd(); } } } return responseBody; }
/// <summary> /// Initializes a new instance of the <see cref="HttpWebRequestCallbackState"/> class. /// </summary> /// <param name="response">The response.</param> /// <param name="state">The state.</param> public HttpWebRequestCallbackState(HttpWebResponse response, object state) { StatusCode = response.StatusCode; Headers = response.Headers; ContentType = response.ContentType.Split(new[] { ';' })[0]; ContentLength = response.ContentLength; var contentEncoding = response.Headers[HttpResponseHeader.ContentEncoding] ?? string.Empty; if (contentEncoding.Contains("gzip")) { ResponseStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); } else if (contentEncoding.Contains("deflate")) { ResponseStream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress); } else { ResponseStream = response.GetResponseStream(); } Log.Debug(m => m("HttpWebRequestCallbackState Ctor statusCode:{0}, contentLength:{1}, contentType:{2}", StatusCode, ContentLength, ContentType)); State = state; }
private string ResponseDebugString(System.Net.HttpWebResponse response) { StringBuilder sb = new StringBuilder(); if (response != null) { sb.AppendFormat("URI = {0}\r\n", response.ResponseUri.ToString()); sb.AppendFormat("Response Code = {0}-{1}\r\n", ((int)response.StatusCode).ToString(), response.StatusCode.ToString()); foreach (var key in response.Headers.AllKeys) { sb.AppendFormat("{0} = {1}\r\n", key, response.Headers[key]); } if (response.ContentLength > 0) { sb.Append("Body:\r\n"); if (response.ContentType.ToLower().Contains("json")) { sb.Append(FormatJson( GetStringFromStream( response.GetResponseStream()))); } else { sb.Append(GetStringFromStream(response.GetResponseStream())); } } else { sb.Append("No body."); } } return(sb.ToString()); }
public static string GetHttpWebResponseData(HttpWebResponse response) { string data = string.Empty; if (response != null) { StreamReader incomingStreamReader = new StreamReader(response.GetResponseStream()); data = incomingStreamReader.ReadToEnd(); incomingStreamReader.Close(); response.GetResponseStream().Close(); } return data; }
/// <summary> /// /// </summary> /// <param name="Url"></param> /// <param name="strEncoding"></param> /// <returns></returns> public static string GetHtmlFromUrl(string Url, string strEncoding = "UTF-8") { System.Net.HttpWebRequest wReq = (HttpWebRequest)HttpWebRequest.Create(Url); wReq.Headers.Add("Accept-Encoding", "gzip"); // Get the response instance. System.Net.HttpWebResponse response = (HttpWebResponse)wReq.GetResponse(); System.IO.Stream respStream = response.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) //using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(strEncoding))) //{ // return reader.ReadToEnd(); //} string responseBody = string.Empty; if (response.ContentEncoding.ToLower().Contains("gzip")) { using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(strEncoding))) { responseBody = reader.ReadToEnd(); } } } else if (response.ContentEncoding.ToLower().Contains("deflate")) { using (DeflateStream stream = new DeflateStream( response.GetResponseStream(), CompressionMode.Decompress)) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(strEncoding))) { responseBody = reader.ReadToEnd(); } } } else { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(strEncoding))) { responseBody = reader.ReadToEnd(); } } } LogManager.GetLogger("ShareController").Debug(responseBody.Replace("{", "#").Replace("}", "##")); return(responseBody); }
public override async Task<string> ReadResponseStream(HttpWebResponse response) { string result = ""; Stream stream = (string.Equals(response.Headers[HttpRequestHeader.ContentEncoding], "gzip", StringComparison.OrdinalIgnoreCase)) ? await Task.Run(() => (response.GetResponseStream().Decompress()) ) : response.GetResponseStream(); using (var reader = new StreamReader(stream)) { result = await reader.ReadToEndAsync(); } return result; }
public override async Task<string> ReadResponseStream(HttpWebResponse response) { string result; using (var gzipStream = (string.Equals(response.Headers["Content-Encoding"], "gzip", StringComparison.CurrentCultureIgnoreCase)) ? new GZipStream(response.GetResponseStream(), CompressionMode.Decompress) : response.GetResponseStream()) { using (var sr = new StreamReader(gzipStream)) { result = await sr.ReadToEndAsync(); } } return result; }
/// <summary> /// 将组建好的xml发送的nc数据平台 /// </summary> /// <param name="strXML">xml</param> /// <param name="strReceiver">服务器地址+账套号</param> /// <returns></returns> public string sendToNC(string strXML, string strReceiverZt) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strReceiverZt + ""); byte[] xmlByte = System.Text.Encoding.Default.GetBytes(strXML); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentType = "text/XML";//SOAP request.ContentLength = xmlByte.Length; // 发送XML(需要考虑编码集问题) System.IO.Stream requestStream = request.GetRequestStream(); requestStream.Write(xmlByte, 0, xmlByte.Length); //接收结果 System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); byte[] result = new byte[20000]; responseStream.Read(result, 0, result.Length); //返回结果转换字符串(需要考虑编码集问题) String resultStr = System.Text.Encoding.UTF8.GetString(result); requestStream.Close(); responseStream.Close(); return(resultStr); }
/// <summary> /// post数据到消息服务接口中 /// </summary> /// <param name="url">消息服务地址 目前为:http://192.168.50.94:7007</param> /// <param name="param">post提交的json参数 示例数据:{"FromSys":"WCF","MsgType":"IM.Alert","Sender":"zhengguilong","SenderName":"郑桂 ","Target":"zhengguilong","Flag":"0","MsgId":"WCF201801280559300052","MSTitle":"数据收集任务完成通知","MSContent":"【测试新增任务】已完成收集,请到系统查看,http://192.168.50.72/Tasks/TaskInfo.aspx?taskid=cbfc8758-f133-ec8a-1346-552c2915a3d0","TargetTime":"2018-01-28 05:59:25","Priority":"3"}</param> /// <returns></returns> public static string PostToServer(string url, string param) { System.Net.HttpWebRequest request; request = (System.Net.HttpWebRequest)WebRequest.Create(url); request.Timeout = 10 * 1000; request.Method = "POST"; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(param); //*******************这几行很关键 request.ContentLength = bytes.Length; request.KeepAlive = false; request.ServicePoint.Expect100Continue = false; //******************* Stream writer = request.GetRequestStream(); writer.Write(bytes, 0, bytes.Length); writer.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); string line = ""; string result = ""; StreamReader reader = new StreamReader(stream, Encoding.UTF8); while ((line = reader.ReadLine()) != null) { result += line + "\r\n"; } return(result); }
public static long GetPlusOnes(string url) { string googleApiUrl = "https://clients6.google.com/rpc?key=AIzaSyBjTBm1HZzlKd1EBcQ3QCCgWfy21kxjvwA"; string postData = @"[{""method"":""pos.plusones.get"",""id"":""p"",""params"":{""nolog"":true,""id"":""" + url + @""",""source"":""widget"",""userId"":""@viewer"",""groupId"":""@self""},""jsonrpc"":""2.0"",""key"":""p"",""apiVersion"":""v1""}]"; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(googleApiUrl); request.Method = "POST"; request.ContentType = "application/json-rpc"; request.ContentLength = postData.Length; System.IO.Stream writeStream = request.GetRequestStream(); UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(postData); writeStream.Write(bytes, 0, bytes.Length); writeStream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8); string jsonString = readStream.ReadToEnd(); readStream.Close(); responseStream.Close(); response.Close(); JObject json = JObject.Parse(jsonString); //var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(jsonString); long count = Convert.ToInt32(json[0]["result"]["metadata"]["globalCounts"]["count"].ToString().Replace(".0", "")); return(count); }
public void DownloadFile(string URL, string filename) { try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); byte[] by = new byte[1024]; int realReadLen = st.Read(by, 0, by.Length); long progressBarValue = 0; while (realReadLen > 0) { so.Write(by, 0, realReadLen); progressBarValue += realReadLen; pbDown.Dispatcher.BeginInvoke(new ProgressBarSetter(SetProgressBar), progressBarValue); realReadLen = st.Read(by, 0, by.Length); } so.Close(); st.Close(); } catch (System.Exception) { throw; } }
private PageInfo ExtractFromResponse(HttpWebResponse response) { var info = new PageInfo(); using (var responseStream = response.GetResponseStream()) { var htmlDocument = new HtmlDocument(); htmlDocument.Load(responseStream); htmlDocument.OptionFixNestedTags = true; var quote = htmlDocument.DocumentNode .SelectSingleNode("//body") .SelectNodes("//p").Where(a => a.Attributes.Any(x => x.Name == "class" && x.Value == "qt")) .SingleOrDefault(); var title = htmlDocument.DocumentNode .SelectSingleNode("//title"); //Quote might not be found, bash.org doesn't have a 404 page if (quote == null || title == null) { return null; } //Strip out any HTML that isn't defined in the WhiteList SanitizeHtml(quote); info.Quote = quote.InnerHtml; info.PageURL = response.ResponseUri.AbsoluteUri; info.QuoteNumber = title.InnerHtml; } return info; }
/// <summary> /// 获得企业用户余额 /// </summary> /// <returns></returns> public int GetFee() { try { string DstUrl = string.Format("http://www.china-sms.com/send/getfee.asp?name={0}&pwd={1}", this.Name, this.Pwd); System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)System.Net.HttpWebRequest.Create(DstUrl).GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(rs.GetResponseStream(), this.Encoding); this.Return = sr.ReadToEnd(); Regex rx = new Regex(this.GetFeeRegexPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); Match match = rx.Match(this.Return); var retobj = new { id = 0, err = "企业用户验证失败", errid = 6010, company = "" }; if (match.Success && match.Groups.Count == 5) { retobj = new { id = int.Parse(match.Groups[1].Value), err = match.Groups[2].Value, errid = int.Parse(match.Groups[3].Value), company = match.Groups[4].Value }; } return(retobj.id); } catch { return(0); } }
public static string WebPagePostGet(string url, string data, Encoding code) { try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] byte1 = Encoding.UTF8.GetBytes(data); request.ContentLength = byte1.Length; Stream newStream = request.GetRequestStream(); // Send the data. newStream.Write(byte1, 0, byte1.Length); //写入参数 newStream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); Encoding coding = code; System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), coding); string s = reader.ReadToEnd(); reader.Close(); reader.Dispose(); response.Close(); reader = null; response = null; request = null; return(s); } catch (Exception e) { return("ERROR"); } }
/// <summary> /// 下载带进度条代码(普通进度条) /// </summary> /// <param name="URL">网址</param> /// <param name="Filename">文件名</param> /// <param name="Prog">普通进度条ProgressBar</param> /// <returns>True/False是否下载成功</returns> public bool DownLoadFile(string URL, string Filename, ToolStripProgressBar Prog) { try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); //从URL地址得到一个WEB请求 System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); //从WEB请求得到WEB响应 long totalBytes = myrp.ContentLength; //从WEB响应得到总字节数 Prog.Visible = true; Prog.Maximum = (int)totalBytes; //从总字节数得到进度条的最大值 System.IO.Stream st = myrp.GetResponseStream(); //从WEB请求创建流(读) System.IO.Stream so = new System.IO.FileStream(Filename, System.IO.FileMode.Create); //创建文件流(写) long totalDownloadedByte = 0; //下载文件大小 byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); //读流 while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; //更新文件大小 Application.DoEvents(); so.Write(by, 0, osize); //写流 Prog.Value = (int)totalDownloadedByte; //更新进度条 osize = st.Read(by, 0, (int)by.Length); //读流 } so.Close(); //关闭流 st.Close(); //关闭流 Prog.Visible = false; return(true); } catch { return(false); } }
internal Response(HttpWebResponse response) { using (response) { using (Stream response_stream = response.GetResponseStream()) { if (response_stream.CanRead) { byte[] buffer = new byte[16654]; int read; using (MemoryStream s = new MemoryStream()) { while((read = response_stream.Read(buffer, 0, buffer.Length)) > 0) { s.Write(buffer, 0, read); } Body = new byte[s.Length]; s.Seek(0, SeekOrigin.Begin); s.Read(Body, 0, Body.Length); } } } Status = response.StatusCode; ContentType = response.GetResponseHeader("Content-Type"); ETag = response.GetResponseHeader("ETag"); } }
public virtual string ReadResponse(HttpWebResponse response) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } }
private string getRequestObject(string urlString, string method, System.Collections.Hashtable queryStrings, bool isIncludeToken, string postBody) { if (queryStrings != null) { urlString += "?"; foreach (string key in queryStrings.Keys) { urlString += key + "=" + System.Web.HttpUtility.UrlEncode(queryStrings[key].ToString()) + "&"; } } System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(urlString); //httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.ContentType = "text/json"; httpWebRequest.Method = method; if (isIncludeToken) { httpWebRequest.Headers.Add("token", token); } if (!string.IsNullOrEmpty(postBody)) { byte[] buf = Encoding.UTF8.GetBytes(postBody); httpWebRequest.ContentLength = buf.Length; Stream stream = httpWebRequest.GetRequestStream(); stream.Write(buf, 0, buf.Length); stream.Close(); } System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); Stream receiveStream = httpWebResponse.GetResponseStream(); System.IO.StreamReader streamReader = new System.IO.StreamReader(receiveStream, System.Text.Encoding.UTF8); string jsonstring = streamReader.ReadToEnd(); return(jsonstring); }
public Boolean checkUpdates() { System.Net.HttpWebRequest request = (HttpWebRequest)System.Net.HttpWebRequest.Create("http://myvmkpal.com/update/version.txt"); System.Net.HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()); string newestversion = sr.ReadToEnd(); if (newestversion == currentversion) { return(false); } else { DialogResult dialogResult = MessageBox.Show("A new version of MyVMK Pal (" + newestversion + ") is available. Would you like to download it now?", "Update Available", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { Process process = null; ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = Directory.GetCurrentDirectory() + "\\Updater.exe"; processStartInfo.Verb = "runas"; processStartInfo.WindowStyle = ProcessWindowStyle.Normal; processStartInfo.UseShellExecute = true; process = Process.Start(processStartInfo); //System.Diagnostics.Process.Start(Directory.GetCurrentDirectory() + "\\Updater.exe"); //process.Dispose(); //form.Close(); //Environment.Exit(0); } } return(true); }
public string ProcessResponse(System.Net.HttpWebResponse Response, bool AddHeaders = false) { StringBuilder Html = new StringBuilder(); Stream receiveStream = Response.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(receiveStream, encode); Char[] read = new Char[257]; int count = readStream.Read(read, 0, 256); if (AddHeaders == true) { Html.Append(Response.Headers.ToString()); } while (count > 0) { String str = new String(read, 0, count); Html.Append(str); count = readStream.Read(read, 0, 256); } readStream.Close(); Response.Close(); return(Html.ToString()); }
public static bool DownloadFile(Uri url, string destFileName, HttpWebResponse response, CancellationToken? token = null, Action<int> indicateProgress = null) { using (new ProfileSection("Download file", typeof(WebRequestHelper))) { ProfileSection.Argument("url", url); ProfileSection.Argument("destFileName", destFileName); ProfileSection.Argument("response", response); ProfileSection.Argument("token", token); ProfileSection.Argument("indicateProgress", indicateProgress); using (var responseStream = response.GetResponseStream()) { try { Assert.ArgumentNotNull(responseStream, "responseStream"); responseStream.ReadTimeout = Settings.CoreWebDownloadTimeoutMinutes.Value * Minute; DownloadFile(destFileName, responseStream, token, indicateProgress); ProfileSection.Result("Done"); return true; } catch (OperationCanceledException) { FileSystem.FileSystem.Local.File.Delete(destFileName); ProfileSection.Result("Canceled"); return false; } catch (Exception ex) { throw new InvalidOperationException("Downloading failed with exception", ex); } } } }
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; }
private static string GetSchemaString(HttpWebResponse response) { string result; var reader = new StreamReader(response.GetResponseStream()); result = reader.ReadToEnd(); return result; }
protected void Page_Load(object sender, EventArgs e) { try { if (!IsPostBack) { string ipaddress; string strHostName = System.Net.Dns.GetHostName(); string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString(); string clientip = clientIPAddress.ToString(); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("http://www.whatismyip.org"); request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE" + "6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); using (System.IO.StreamReader reader = new StreamReader(response.GetResponseStream())) { ipaddress = reader.ReadToEnd(); reader.Close(); } lblip.Text = ipaddress.ToString(); DataTable dt = GetLocation(ipaddress.ToString()); lblcountry.Text = dt.Rows[0]["CountryName"].ToString(); lblregion.Text = dt.Rows[0]["RegionName"].ToString(); lblcity.Text = dt.Rows[0]["City"].ToString(); response.Close(); } } catch (Exception) { throw; } }
protected void hlinkCreate_Click(object sender, System.EventArgs e) { string host = this.Page.Request.Url.Host; string str = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(host + "A9jkLUxm", "MD5").ToLower(); string requestUriString = "http://wss.cnzz.com/user/companion/92hi.php?domain=" + host + "&key=" + str; System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(requestUriString); System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); System.IO.Stream responseStream = httpWebResponse.GetResponseStream(); responseStream.ReadTimeout = 100; System.IO.StreamReader streamReader = new System.IO.StreamReader(responseStream); string text = streamReader.ReadToEnd().Trim(); streamReader.Close(); if (text.IndexOf("@") == -1) { this.ShowMsg("创建账号失败", false); return; } SiteSettings siteSettings = HiContext.Current.SiteSettings; string[] array = text.Split(new char[] { '@' }); siteSettings.CnzzUsername = array[0]; siteSettings.CnzzPassword = array[1]; siteSettings.EnabledCnzz = false; this.div_pan1.Visible = false; this.div_pan2.Visible = true; this.hplinkSet.Text = "开启统计功能"; SettingsManager.Save(siteSettings); this.ShowMsg("创建账号成功", true); }
public static string RemoteVersion(string url) { string rv = ""; try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse(); System.IO.Stream receiveStream = response.GetResponseStream(); System.IO.StreamReader readStream = new System.IO.StreamReader(receiveStream, Encoding.UTF8); string s = readStream.ReadToEnd(); response.Close(); if (ValidateFile(s)) { rv = s; } } catch (Exception exception) { // Anything could have happened here but // we don't want to stop the user // from using the application. rv = null; App.SendReport(exception, "Couldnt Find the Remote Version of NS"); } return(rv); }
private string ProcessContent(HttpWebResponse response) { SetEncodingFromHeader(response); Stream s = response.GetResponseStream(); if (response.ContentEncoding.ToLower().Contains("gzip")) s = new GZipStream(s, CompressionMode.Decompress); else if (response.ContentEncoding.ToLower().Contains("deflate")) s = new DeflateStream(s, CompressionMode.Decompress); MemoryStream memStream = new MemoryStream(); int bytesRead; byte[] buffer = new byte[0x1000]; for (bytesRead = s.Read(buffer, 0, buffer.Length); bytesRead > 0; bytesRead = s.Read(buffer, 0, buffer.Length)) { memStream.Write(buffer, 0, bytesRead); } s.Close(); string html; memStream.Position = 0; using (StreamReader r = new StreamReader(memStream, Encoding)) { html = r.ReadToEnd().Trim(); html = CheckMetaCharSetAndReEncode(memStream, html); } return html; }
public static DateTime?GetNistTime() { DateTime?dateTime = null; try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b"); request.Method = "GET"; request.Timeout = 3000; request.Accept = "text/html, application/xhtml+xml, */*"; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)"; request.ContentType = "application/x-www-form-urlencoded"; request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); //No caching System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { StreamReader stream = new StreamReader(response.GetResponseStream()); string html = stream.ReadToEnd();//<timestamp time=\"1395772696469995\" delay=\"1395772696469995\"/> string time = Regex.Match(html, @"(?<=\btime="")[^""]*").Value; double milliseconds = Convert.ToInt64(time) / 1000.0; dateTime = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToLocalTime(); } } catch { } return(dateTime); }
public static string readfromWeb(string path) { string lcUrl = null; lcUrl = path; // *** Establish the request System.Net.HttpWebRequest loHttp = (HttpWebRequest)System.Net.HttpWebRequest.Create(lcUrl); // *** Set properties var timeout = 120; //seconds loHttp.Timeout = timeout * 1000; loHttp.ReadWriteTimeout = timeout * 1000; loHttp.UserAgent = "Code Sample Web Client"; Logger.WriteLine(String.Format("Downlading {0}", path)); // *** Retrieve request info headers System.Net.HttpWebResponse loWebResponse = (HttpWebResponse)loHttp.GetResponse(); Encoding enc = Encoding.GetEncoding(65001); //Dim enc As Encoding = Encoding.GetEncoding(65001) //Dim enc As Encoding = Encoding.GetEncoding(1252) //// Windows default Code Page System.IO.StreamReader loResponseStream = new System.IO.StreamReader(loWebResponse.GetResponseStream(), enc); string lcHtml = loResponseStream.ReadToEnd(); loWebResponse.Close(); loResponseStream.Close(); return(lcHtml); }
public void Handle(HttpWebResponse proxyResponse, HttpResponse contextResponse) { //add cookie //foreach (var cookieName in proxyResponse.Cookies) //{ // var proxyCookie = proxyResponse.Cookies[cookieName.ToString()]; // if(proxyCookie.Name.StartsWith("Proxy_")) // contextResponse.SetCookie(new HttpCookie(proxyCookie.Name, proxyCookie.Value)); //} //contextResponse.SetCookie(new HttpCookie("proxyHost", proxyResponse.ResponseUri.Host)); //add Content-Type contextResponse.ContentType = proxyResponse.ContentType; //contextResponse //add Content-Length //Content-Encoding //contextResponse.Headers["Content-Encoding"] = proxyResponse.ContentEncoding; //copy stream using (Stream responseStream = proxyResponse.GetResponseStream()) { Stream rwStream = RewriteStream(responseStream,proxyResponse.ResponseUri, proxyResponse.ContentType); //contextResponse.Headers["Content-Length"] = rwStream.Length.ToString(); rwStream.CopyToStream(contextResponse.OutputStream); rwStream.Close(); } }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <returns></returns> internal static PagSeguroServiceException CreatePagSeguroServiceException(HttpWebResponse response) { if (response == null) throw new PagSeguroServiceException("response answered with null value"); if (response.StatusCode == HttpStatusCode.OK) throw new ArgumentException("response.StatusCode must be different than HttpStatusCode.OK", "response"); using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { switch (response.StatusCode) { case HttpStatusCode.BadRequest: List<ServiceError> errors = new List<ServiceError>(); try { ErrorsSerializer.Read(reader, errors); } catch (XmlException e) { return new PagSeguroServiceException(response.StatusCode, e); } return new PagSeguroServiceException(response.StatusCode, errors); default: return new PagSeguroServiceException(response.StatusCode); } } }
public string GetResponseContent(HttpWebResponse response) { if (response == null) { throw new ArgumentNullException("response"); } string responseFromServer = null; try { // Get the stream containing content returned by the server. using (Stream dataStream = response.GetResponseStream()) { // Open the stream using a StreamReader for easy access. using (StreamReader reader = new StreamReader(dataStream)) { // Read the content. responseFromServer = reader.ReadToEnd(); // Cleanup the streams and the response. } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { response.Close(); } LastResponse = responseFromServer; return responseFromServer; }
public HttpResponse(HttpWebRequest con) { this.con = con; this.rsp = (HttpWebResponse)con.GetResponse(); this.stream = rsp.GetResponseStream(); this.reader = new StreamReader(stream, Encoding.UTF8); }
public static Image DownloadBinaryFromInternet(string Inurl) { Uri url = new Uri(Inurl); string urlHost = url.Host; Image BookmarkIcon = null; if (url.HostNameType == UriHostNameType.Dns) { string iconUrl = Inurl; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(iconUrl); System.Net.HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); BookmarkIcon = Image.FromStream(stream); } catch (Exception exp) { AppController.Current.Logger.writeToLogfile(exp); } return(BookmarkIcon); } else { return(null); } }
public static string PostData(string strPostData) { LogHelper.WriteLog("start postData="); LogHelper.WriteLog(strPostData); LogHelper.WriteLog("end postData!"); HttpWebRequest r = HttpWebRequest.Create(url) as HttpWebRequest; r.Method = "POST"; r.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"; r.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"; r.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; string postData = strPostData; byte[] data = Encoding.UTF8.GetBytes(postData); r.ContentLength = data.Length; Stream newStream = r.GetRequestStream(); // Send the data. newStream.Write(data, 0, data.Length); newStream.Close(); System.Net.HttpWebResponse response = r.GetResponse() as System.Net.HttpWebResponse; string tempresult = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd(); return(tempresult); }
public static string DoPost(string url, Hashtable paramsOfUrl) { if (url == null) { throw new Exception("WebService地址为空"); } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); // 编辑并Encoding提交的数据 byte[] data = GetJointBOfParams(paramsOfUrl); // 发送请求 request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); // 获得回复 System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string result = reader.ReadToEnd(); reader.Close(); return(result); }
public virtual string GetContent(HttpWebResponse webResp, Encoding encoding) { string content = null; var countTry = 3; var repeat = true; while (repeat && countTry > 0) try { var responseStream = webResp.GetResponseStream(); responseStream.ReadTimeout = 8000; using (var sr = new StreamReader(responseStream, encoding)) { content = sr.ReadToEnd(); repeat = false; } } catch (WebException exWeb) { countTry--; File.AppendAllText("log.txt", exWeb.Message + Environment.NewLine); File.AppendAllText("log.txt", "++" + Environment.NewLine); File.AppendAllText("log.txt", exWeb.Status.ToString() + Environment.NewLine); File.AppendAllText("log.txt", "++" + Environment.NewLine); File.AppendAllText("log.txt", "GetContent" + Environment.NewLine); File.AppendAllText("log.txt", "------" + Environment.NewLine); var webReq = GetHttpWebReq(url); webResp = GetHttpWebResp(webReq); } return content; }
public void DownloadFile(string URL, string filename) { float percent = 0; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; System.IO.Stream st = myrp.GetResponseStream(); System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; System.Windows.Forms.Application.DoEvents(); so.Write(by, 0, osize); osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * 100; int mypercent = (int)percent; System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 } so.Close(); st.Close(); } catch (Exception downee) { MessageBox.Show(downee.ToString() + "\n\n简短解释:\n下载出错,请检查是否有目录权限;磁盘空间是否已满;若无法解决请进群咨询管理员"); } }
private IEnumerable<ITwitterExceptionInfo> GetStreamInfo(HttpWebResponse wexResponse) { using (var stream = wexResponse.GetResponseStream()) { return GetTwitterExceptionInfosFromStream(stream); } }
public string GetTitle() { string title = ""; System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(BaseURL); FormMain.UserConfig.SetProxy(webReq); System.Net.HttpWebResponse webRes = null; try { webRes = (System.Net.HttpWebResponse)webReq.GetResponse(); string returnText; System.IO.Stream resStream = webRes.GetResponseStream(); using (System.IO.StreamReader sr = new System.IO.StreamReader(resStream, GetEncoding())) { returnText = sr.ReadToEnd(); } Regex rx = new Regex("<title>(.*?)</title>", RegexOptions.Singleline | RegexOptions.IgnoreCase); Match m = rx.Match(returnText); if (m.Success) { title = HttpUtility.HtmlDecode(m.Groups[1].Value); } } catch (Exception e) { FormMain.Instance.AddLog(e.Message); } return(title); }
public string GenerateMiniQR(string accessToken, string path) { string postUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken; HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest; request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8"; string options = $"{{\"path\":\"{path}\"}}"; byte[] payload = Encoding.UTF8.GetBytes(options); request.ContentLength = payload.Length; Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); List <byte> bytes = new List <byte>(); int temp = stream.ReadByte(); while (temp != -1) { bytes.Add((byte)temp); temp = stream.ReadByte(); } byte[] result = bytes.ToArray(); string base64 = Convert.ToBase64String(result);//将byte[]转为base64 return(base64); }
public static WebResponse ExtractResponse( HttpWebResponse response, string filename ) { WebResponse webResponse = null; Stream streamResponse = response.GetResponseStream(); #if !SILVERLIGHT if ( response.ContentEncoding.ToLower().Contains( "deflate" ) ) streamResponse = new DeflateStream( streamResponse, CompressionMode.Decompress ); else if ( response.ContentEncoding.ToLower().Contains( "gzip" ) ) streamResponse = new GZipStream( streamResponse, CompressionMode.Decompress ); #endif StreamReader streamRead = null; try { webResponse = new WebResponse(); webResponse.ResponseBytes = NetworkUtils.StreamToByteArray( streamResponse ); webResponse.ResponseString = NetworkUtils.ByteArrayToStr( webResponse.ResponseBytes ); if ( !string.IsNullOrEmpty( filename ) ) MXDevice.File.Save(filename, webResponse.ResponseBytes); } finally { // Close the stream object if ( streamResponse != null ) streamResponse.Close(); if ( streamRead != null ) streamRead.Close(); } return webResponse; }
/// <summary> /// Initializes a new instance of the <see cref="MadMimi.Result"/> class. /// </summary> /// <param name='response'> /// An HttpWebResponse which contains the result. /// </param> public Result(HttpWebResponse response) { statusCode = response.StatusCode; using (StreamReader reader = new StreamReader (response.GetResponseStream ())) { body = reader.ReadToEnd (); } }
public void Request(string url) { var timer = new Stopwatch(); var respBody = new StringBuilder(); _request = (HttpWebRequest) WebRequest.Create(url); try { timer.Start(); _response = (HttpWebResponse) _request.GetResponse(); var buf = new byte[8192]; 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); timer.Stop(); _responseBody = respBody.ToString(); _statusCode = (int) _response.StatusCode; _responseTime = timer.ElapsedMilliseconds/1000.0; } catch (WebException ex) { _response = (HttpWebResponse) ex.Response; _responseBody = "No Server Response"; _escapedBody = "No Server Response"; _responseTime = 0.0; } }
/// <summary> /// Initializes a new instance of the <see cref="NetworkDirectWebResponse"/> class. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="response">The response.</param> internal NetworkDirectWebResponse(Uri requestUri, HttpWebResponse response) : base(requestUri, response) { Contract.Requires<ArgumentNullException>(requestUri != null); Contract.Requires<ArgumentNullException>(response != null); this.httpWebResponse = response; this.responseStream = response.GetResponseStream(); }
/// <summary> /// 执行请求,请求接口失败时抛出异常 /// </summary> /// <typeparam name="T">请求的类型</typeparam> /// <typeparam name="S">返回的类型</typeparam> /// <param name="requestType">接口名称</param> /// <param name="obj">请求的参数Json对象</param> /// <returns>返回的类型的对象</returns> public static S Request <T, S>(T obj) { string str = jss.Serialize(obj); string paraUrlCoded = KeyValueCombination(str); string strURL = @"http://api.fanyi.baidu.com/api/trans/vip/translate"; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(strURL); request.UserAgent = "User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"; request.ContentType = "application/x-www-form-urlencoded"; request.Credentials = CredentialCache.DefaultCredentials; request.Method = "POST"; request.Proxy = null; request.Timeout = 60000; byte[] payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded); request.ContentLength = payload.Length; System.IO.Stream writer = request.GetRequestStream(); writer.Write(payload, 0, payload.Length); writer.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string responseText = myreader.ReadToEnd(); myreader.Close(); return(jss.Deserialize <S>(responseText)); }
public string GetContent(HttpWebResponse webResp, Encoding encoding) { string content = null; var countTry = 3; var repeat = true; while (repeat && countTry > 0 && webResp != null) try { var responseStream = webResp.GetResponseStream(); responseStream.ReadTimeout = 8000; using (var sr = new StreamReader(responseStream, encoding)) { content = sr.ReadToEnd(); webResp = null; if (content.Equals("обновите страницу, пожалуйста")) throw new WebException("ParsersChe error: Proxy no Russian"); repeat = false; } } catch (WebException exWeb) { countTry--; content = null; Log(exWeb, "GetContent"); var webReq = GetHttpWebReqNewProxy(url); if (webReq != null) webResp = GetHttpWebResp(webReq); } return content; }
public bool DownloadImage(HttpWebResponse webResp, string fileName) { var result = false; var countTry = 3; var repeat = true; while (repeat && countTry > 0 && webResp != null) { // if the remote file was found, download it try { using (var inputStream = webResp.GetResponseStream()) using (var outputStream = File.OpenWrite(fileName)) { var buffer = new byte[4096]; int bytesRead; do { bytesRead = inputStream.Read(buffer, 0, buffer.Length); outputStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); } result = true; repeat = false; } catch { } } return result; }
/// <summary> /// Initializes a new instance of the <see cref="NetworkDirectWebResponse"/> class. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="response">The response.</param> internal NetworkDirectWebResponse(Uri requestUri, HttpWebResponse response) : base(requestUri, response) { Requires.NotNull(requestUri, "requestUri"); Requires.NotNull(response, "response"); this.httpWebResponse = response; this.responseStream = response.GetResponseStream(); }
public string GetContent(HttpWebResponse webResp, Encoding encoding) { var content = string.Empty; Stream responseStream = null; try { try { responseStream = webResp.GetResponseStream(); using (var sr = new StreamReader(responseStream, encoding)) { responseStream = null; content = sr.ReadToEnd(); } } finally { if (responseStream != null) responseStream.Dispose(); } } catch (Exception) { } return content; }
private static string ReadContentFromResult(HttpWebResponse response) { using (var reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } }
public string Reporttoserver(string status, string testname, ref string error, string emailaddress) { vartestname = testname; varstatus = status; varerror = error; count += 1; if(status == "Complete" && emailaddress.Length > 5) email(emailaddress); string responsestring = "."; try { req = (HttpWebRequest)WebRequest.Create("http://nz-hwlab-ws1:80/dashboard/update/?script=" + testname + "&status=" + status); //Complete resp = (HttpWebResponse)req.GetResponse(); Stream istrm = resp.GetResponseStream(); int ch; for (int ij = 1; ; ij++) { ch = istrm.ReadByte(); if (ch == -1) break; responsestring += ((char)ch); } resp.Close(); //email(); return responsestring + " : from server"; } catch (System.Net.WebException e) { error = e.Message; System.Console.WriteLine(error); string c = count.ToString(); return "ServerError " + c; } }