private static void DisposeObject(ref HttpWebRequest request, ref HttpWebResponse response, ref Stream responseStream, ref StreamReader reader) { if (request != null) { request = null; } if (response != null) { response.Close(); response = null; } if (responseStream != null) { responseStream.Close(); responseStream.Dispose(); responseStream = null; } if (reader != null) { reader.Close(); reader.Dispose(); reader = null; } }
string GetURLContent(string url, string EncodingType) { string PetiResp = ""; Stream mystream; //"http://www.baidu.com" //"utf-8" System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); req.AllowAutoRedirect = true; System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse(); if (resp.StatusCode == System.Net.HttpStatusCode.OK) { mystream = resp.GetResponseStream(); System.Text.Encoding encode = System.Text.Encoding.GetEncoding(EncodingType); StreamReader readStream = new StreamReader(mystream, encode); char[] cCont = new char[500]; int count = readStream.Read(cCont, 0, 256); while (count > 0) { // Dumps the 256 characters on a string and displays the string to the console. String str = new String(cCont, 0, count); PetiResp += str; count = readStream.Read(cCont, 0, 256); } resp.Close(); return(PetiResp); } resp.Close(); return(null); }
public bool ConnectionAvailable() { try { req = (HttpWebRequest)WebRequest.Create("http://www.google.com"); resp = (HttpWebResponse)req.GetResponse(); if (HttpStatusCode.OK == resp.StatusCode) { // HTTP = 200 - Интернет безусловно есть! resp.Close(); return true; } else { // сервер вернул отрицательный ответ, возможно что инета нет resp.Close(); return false; } } catch (WebException) { // Ошибка, значит интернета у нас нет. Плачем :'( return false; } }
public WebResponse(HttpWebRequest request, HttpWebResponse response) { _requestContentType = request == null ? null : request.ContentType; _response = response; _headers = new NameValueDictionary(response == null ? new System.Collections.Specialized.NameValueCollection() : response.Headers); _content = new MemoryStream(); if (_response != null) { using (var stream = _response.GetResponseStream()) { stream.CopyTo(_content); } _content.Position = 0; _response.Close(); } #if !NET4 if (request.CookieContainer != null && response.Cookies.Count > 0) { request.CookieContainer.BugFix_CookieDomain(); } #endif }
public Login(string Username, string Password) { string url = string.Format("http://www.myfitnesspal.com/account/login"); request = (HttpWebRequest)WebRequest.Create(url); request.AllowAutoRedirect = false; request.CookieContainer = new CookieContainer(); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; string NewValue = string.Format("username={0}&password={1}&remember_me=1",Username,Password); request.ContentLength = NewValue.Length; // Write the request StreamWriter stOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); stOut.Write(NewValue); stOut.Close(); // Do the request to get the response response = (HttpWebResponse)request.GetResponse(); StreamReader stIn = new StreamReader(response.GetResponseStream()); string strResponse = stIn.ReadToEnd(); stIn.Close(); cookies = request.CookieContainer; response.Close(); }
private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); switch (rsp.ContentEncoding) { case "gzip": stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); break; case "deflate": stream = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Decompress); break; } reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } }
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 static bool Connect() { //インターネットに接続されているか確認する string host = "http://www.yahoo.com"; System.Net.HttpWebRequest webreq = null; System.Net.HttpWebResponse webres = null; try { //HttpWebRequestの作成 webreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(host); //メソッドをHEADにする webreq.Method = "HEAD"; //受信する webres = (System.Net.HttpWebResponse)webreq.GetResponse(); return(true); } catch { return(false); } finally { if (webres != null) { webres.Close(); } } }
/// <summary> /// Outputs the HTTP reponse to the console /// /// Code taken from http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream.aspx /// </summary> /// <param name="response"></param> private static void displayHttpWebReponse(HttpWebResponse response) { Console.WriteLine(response.StatusCode); Stream receiveStream = response.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader(receiveStream, encode); Console.WriteLine("\r\nResponse stream received."); Char[] read = new Char[256]; // Reads 256 characters at a time. int count = readStream.Read(read, 0, 256); Console.WriteLine("HTML...\r\n"); while (count > 0) { // Dumps the 256 characters on a string and displays the string to the console. String str = new String(read, 0, count); Console.Write(str); count = readStream.Read(read, 0, 256); } Console.WriteLine(""); // Releases the resources of the response. response.Close(); // Releases the resources of the Stream. readStream.Close(); }
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; } }
public static HttpRemoteResponse GetRemoteResponse(HttpWebResponse webResponse) { HttpRemoteResponse response = new HttpRemoteResponse(webResponse.StatusCode, GetHeadersDictionaryFrom(webResponse.Headers), GetContentFromStream(webResponse.GetResponseStream())); webResponse.Close(); return response; }
private string GetRawStringFromResponse(HttpWebResponse response) { using (var sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var responseString = sr.ReadToEnd(); response.Close(); return responseString; } }
private string RequestToText(string requestUri) { System.Net.HttpWebRequest hwreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(requestUri); System.Net.HttpWebResponse hwres = (System.Net.HttpWebResponse)hwreq.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(hwres.GetResponseStream()); string result = sr.ReadToEnd(); sr.Close(); hwres.Close(); return(result); }
public Response(HttpWebResponse response, string Format) { if (Format == "xml") { responseFormat = Format; } else { responseFormat = "json"; } setResponseBody(response); response.Close(); }
private static void DisplayResponse(HttpWebResponse hresp, string id) { Trace.WriteLine(null); Trace.WriteLine("*** Response Start ***"); Trace.WriteLine(hresp.StatusCode); Trace.WriteLine(hresp.StatusDescription); DisplayHeaders(hresp.Headers); DisplayContent(hresp, id); hresp.Close(); Trace.WriteLine("*** Response End ***"); Trace.WriteLine(""); }
protected static void printResponseToConsole(HttpWebResponse response) { Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); String responseXml = reader.ReadToEnd(); Console.Out.WriteLine("BlueTarp Auth status code: " + response.StatusCode); Console.Out.WriteLine("BlueTarp Auth Response:"); Console.Out.WriteLine(responseXml); dataStream.Close(); reader.Close(); response.Close(); }
/* * Method: deleteRecording() * Summary: Attempts to delete a recording from the server * Parameter: recJson - A recording string in the JSON format * Returns: True or false depending on the success of the delete operation */ public static bool deleteRecording(string recJson) { // Prepare the DELETE HTTP request to the recordings endpoint prepareRequest(recordingUrl, "text/json", "DELETE"); //RecordingManager recording = new RecordingManager(recJson); bool result = false; try { // Extract the ID from the recJson string string recId = RecordingManager.getRecId(recJson); // Create the JSON object to be written to the server JObject recInfo = new JObject( new JProperty("recId", recId), new JProperty("UserId", Properties.Settings.Default.currentUser)); // Write the JSON string to the server using (var writer = new StreamWriter(request.GetRequestStream())) { writer.Write(recInfo.ToString()); writer.Flush(); writer.Close(); } try { // Retrieve the response response = (HttpWebResponse)request.GetResponse(); // If the response code is "OK", return true if (response.StatusCode == HttpStatusCode.OK) result = true; response.Close(); } catch (WebException we) { Console.WriteLine(we.Message); return false; } } catch (WebException we) { Console.WriteLine(we.Message); result = false; } return result; }
public static String GetContentForResponse(HttpWebResponse response) { Stream stream = response.GetResponseStream(); String characterSet = String.IsNullOrEmpty(response.CharacterSet) ? "UTF-8" : response.CharacterSet; Encoding encoding = Encoding.GetEncoding(characterSet); StreamReader reader = new StreamReader(stream, encoding); String htmlContent = reader.ReadToEnd(); stream.Close(); response.Close(); return htmlContent; }
private static bool Request_krsk_24au_ru(string number, string description, out HttpWebResponse response) { response = null; try { string url = string.Format("http://krsk.24au.ru/{0}/Close/", number); string urlReferer = string.Format("http://krsk.24au.ru/{0}/", number); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.KeepAlive = true; request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0"); request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; request.Headers.Add("Origin", @"http://krsk.24au.ru"); request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"; request.ContentType = "application/x-www-form-urlencoded"; request.Referer = urlReferer; request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch"); request.Headers.Set(HttpRequestHeader.AcceptLanguage, "ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4"); request.Headers.Set(HttpRequestHeader.Cookie, @"_S_STAT=626915f2-8af0-43a1-8d73-cbf70191a504; idCityByIP=464; ASP.NET_SessionId=tvuaywcuob2q4ba35zuzu25a; lvidc=0; Hy701jhkafgPOOYWoehf=D38279808D9765F64517629F22EE250E2741B085E1A556ABE341A9FA6F40852E522857D0C6A9D4CB1A9D262D79FAFA4586FCB7D402358F0FFEB4864AD9D48835; 071ce61de6dafda9cc06b4d262bd0058=; is_adult=0; __atuvc=1%7C7; region=464; KIKkb2k323bJkaASDF923=mxWpVSfzKtAg2GFwAPsHV9ZYyIiX6w_l2jOO0lKZUjxR0j8nNb2k1ZYkEE_5otEOfJhR8uDE_pxZzBeLyH0f0aYOnjRAePnxH4tDsaKJ9iiuONRlAxdF9c81ix6ZeFa9Xs2wDHfVhMrfO3jlY8dL_7JblDVeSDeBAprji5gL3CLP5D8vvePj-zJaICKEvU4yKdSIDGt-HgMMI0a4Iyg_PTIPJgLFL0xy3HwdhHM8ZIxIwzrcL-Sp7hm3iQ-AfkM2PcaTyrXN-yvisA4dQSQUf3jxmRzc9GSxYmDV_0r4zSF6BiXYFLgdhrUkEqNHgSSkNt5XJaXiVTrsQVVuy_A3HEJwhICp-LMW9ditdTUvwZqQg_xka7jlM156e8VJsqVU9wxUT57LQn8Axct7jwlYNixjRVDG6pbdIJO0K4Fk0AC-TosSNfmD5cOwr2BBURc-t1UDG2l32a54hwPsK8ZFVcddamQ76_YuEbiDeqx5LALRIOe5OoxA08zVtS1Yf7VSI2OUF9IqGfFBxbhYGacUlqTxmWveVT3b5vqao1L3kqOb2WsgIQnzZ1M_QGWymK1XjQtLCq8cE-GeIYZc9Lb0DM1XjQySehGwwHw0TCEQnGnZ1dToIA0STmRh5V1LzDJhXJCKiziKLNT4pv5k5MEsp5ci2j281a0H_TNSzoIEFgrPxyOXaZl2tc_d-gdr4p3Q1dCO6BC6JX46eciihID3gF3nyDcNtdlGoGoEfOr_hQbv2QFzzXRzM5wqG7dmA8IRbfuFXv9bv9_DtoiDuvxp1ickJcH4mqoXY1GMmCQFLhdER3X8Wn3W8l8S4LXzsVTDApURA5nMziNdZQSVr5b2j5bOWT8uoemib_7r1QSyDklh0cnZCFsieWmNSzXSiGMP5IpJBfbX3BZ2B-V7VZ4m3f3ABogn5dsE59tVbp1qYqfgbO0xXzCWKOATz0TpOvwk0; _ga=GA1.2.943512218.1390976751"); request.Method = "POST"; request.ServicePoint.Expect100Continue = false; //string body = @"deleteRemark=%D0%BE%D1%88%D0%B8%D0%B1%D0%BA%D0%B0"; string body = "deleteRemark=" + HttpUtility.UrlEncode(description); byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body); request.ContentLength = postBytes.Length; Stream stream = request.GetRequestStream(); stream.Write(postBytes, 0, postBytes.Length); stream.Close(); response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response; else return false; } catch (Exception) { if (response != null) response.Close(); return false; } return true; }
public static void PutFileResponse(HttpWebResponse response, FileContext context, HttpStatusCode? expectedError) { Assert.IsNotNull(response); if (expectedError == null) { Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, response.StatusDescription); FileTestUtils.ETagHeader(response); FileTestUtils.LastModifiedHeader(response); FileTestUtils.RequestIdHeader(response); } else { Assert.AreEqual(expectedError, response.StatusCode, response.StatusDescription); } response.Close(); }
//查询 游戏名字 获取网页信息 public void MnFw() { string gethost = string.Empty; cc = new CookieContainer(); try { //第一次POST请求 string postdata = "keyWords=" + this.txtName.Text + ""; string LoginUrl = "http://lolbox.duowan.com/playerList.php"; requset = (HttpWebRequest)WebRequest.Create(LoginUrl);//实例化Web访问类 requset.Method = "POST";//数据请求方式为POST //模拟头 requset.ContentType = "application/x-www-form-urlencoded"; byte[] postdatabytes = Encoding.UTF8.GetBytes(postdata); requset.ContentLength = postdatabytes.Length; requset.AllowAutoRedirect = false; requset.CookieContainer = cc; requset.KeepAlive = true; //提交请求 stream = requset.GetRequestStream(); stream.Write(postdatabytes, 0, postdatabytes.Length); stream.Close(); //接受响应 response = (HttpWebResponse)requset.GetResponse(); //保存返回cookies response.Cookies = requset.CookieContainer.GetCookies(requset.RequestUri); CookieCollection cook = response.Cookies; string strook = requset.CookieContainer.GetCookieHeader(requset.RequestUri); Cookiesstr = strook; //取第一次GET跳转地址 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string content = sr.ReadToEnd(); response.Close(); strss = content; //登陆成功。 DTView(strss); } catch (Exception) { throw; } }
/// <summary> /// TOP API POST 请求 /// </summary> /// <param name="url">请求容器URL</param> /// <param name="appkey">AppKey</param> /// <param name="appSecret">AppSecret</param> /// <param name="method">API接口方法名</param> /// <param name="session">调用私有的sessionkey</param> /// <param name="param">请求参数</param> /// <returns>返回字符串</returns> public static string Post(string url, string appkey, string appSecret, string method, string session, IDictionary <string, string> param) { #region -----API系统参数---- param.Add("app_key", appkey); param.Add("method", method); param.Add("session", session); param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); param.Add("format", "xml"); param.Add("v", "2.0"); param.Add("sign_method", "md5"); param.Add("sign", CreateSign(param, appSecret)); #endregion string result = string.Empty; #region ---- 完成 HTTP POST 请求---- System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); req.Method = "POST"; req.KeepAlive = true; req.Timeout = 300000; req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; byte[] postData = Encoding.UTF8.GetBytes(PostData(param)); Stream reqStream = req.GetRequestStream(); reqStream.Write(postData, 0, postData.Length); reqStream.Close(); System.Net.HttpWebResponse rsp = (System.Net.HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); Stream stream = null; StreamReader reader = null; stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); result = reader.ReadToEnd(); if (reader != null) { reader.Close(); } if (stream != null) { stream.Close(); } if (rsp != null) { rsp.Close(); } #endregion return(Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "")); }
/// <summary> /// 抓取网页内容 /// </summary> /// <param name="url">网页地址</param> /// <param name="charset">网页编码</param> /// <returns></returns> public static string WebPageContentGet(string url, Encoding code) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); 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); }
/// <summary> /// Copies a HttpWebResponse stream to HttpResponse output stream; also by default copies response internals such as cookies, status, content type /// </summary> /// <param name="input"></param> /// <param name="output"></param> /// <param name="copyInternals"></param> public static void CopyResponse(this System.Net.HttpWebResponse input, HttpResponse output, bool copyInternals = true) { if (input != null) { if (copyInternals) { input.CopyResponseInternals(output); } //copy web request response stream to System.Web.HttpResponse (context.Response) OutputStrem var responseStream = input.GetResponseStream(); responseStream?.CopyTo(output.Body); //Close web request input.Close(); } }
/// <summary> /// 判断一个网络资源是否存在,如果网络异常该方法可能存在0.01秒的延时,所以尽可能异步调用 /// </summary> /// <param name="url"></param> /// <returns></returns> public static bool UrlIsExist(string url) { System.Uri u = null; //exception = null; try { u = new Uri(url); } catch { return(false); } bool isExist = false; System.Net.HttpWebRequest r = System.Net.HttpWebRequest.Create(u) as System.Net.HttpWebRequest; System.Net.HttpWebResponse s = null; r.Proxy = null; r.Timeout = 2000; r.Method = "HEAD"; try { s = r.GetResponse() as System.Net.HttpWebResponse; isExist = (s.StatusCode == System.Net.HttpStatusCode.OK); } catch (System.Net.WebException x) { //exception = x; try { isExist = ((x.Response as System.Net.HttpWebResponse).StatusCode != System.Net.HttpStatusCode.NotFound); x.Response.Close(); } catch { isExist = (x.Status == System.Net.WebExceptionStatus.Success); } } finally { if (s != null) { s.Close(); } } return(isExist); }
/// <summary> /// プラーク情報受信OK /// </summary> /// <param name="json"></param> private void APIUserAuthOkResponse() { n = DateTime.Now; requestTime = n.ToString("yyyy-MM-ddTHH:mm:ss+9:00"); if (requestTime.Length < 24) { requestTime = String.Format("{0:0000}-{1:00}-{2:00}T{3:00}:{4:00}:{5:00}+9:00", n.Year, n.Month, n.Day, n.Hour, n.Minute, n.Second); } var _n = GetUnixTime(n); var nonce = GetNonce(_n); var digest = GetDigest(hex, requestTime, api_Pass, access_Key); var wsse = String.Format("UsernameToken Username={0}, PasswordDigest={1}, Nonce={2}, Created={3}", api_Id, digest, nonce, requestTime); //if (!IP.StartsWith("http")) //{ // IP = "http://" + IP; //} //var url = "http://" + IP + "/WebAPI/plaque_rcv_ok.php"; var url = URL; var req = System.Net.HttpWebRequest.Create(url); req.Method = "POST"; req.Headers.Add("x-wsse", wsse); try { System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse(); var resStream = res.GetResponseStream(); Status = res.StatusCode.ToString(); resStream.Close(); res.Close(); } catch (System.Net.WebException e) { Status = e.Status.ToString(); } catch { } }
public bool RequestFileSize(out long nFileSize) { System.Net.HttpWebRequest webRequest = null; System.Net.HttpWebResponse webResponse = null; nFileSize = 0; if (m_arrURLSorted == null) { if (SetupURLList() == false) { return(false); } if (m_arrURLSorted == null || m_arrURLSorted.Count == 0) { return(false); } } for (int i = 0; i < m_arrURLSorted.Count; i++) { try { webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create((string)m_arrURLSorted.GetByIndex(i)); webRequest.Timeout = 10000; webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse(); nFileSize = webResponse.ContentLength; webResponse.Close(); break; } catch (System.Net.WebException) { continue; } catch (System.Exception) { nFileSize = -1; return(false); } } return(true); }
/// <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> /// Gets the json response. /// </summary> /// <param name="response">The response.</param> /// <returns>System.Object.</returns> public static object GetJsonResponse(HttpWebResponse response) { object jsonResponse = null; if (response == null) return null; using (response) { // ReSharper disable once AssignNullToNotNullAttribute using (var responseReader = new StreamReader(response.GetResponseStream())) { jsonResponse = JsonConvert.DeserializeObject(responseReader.ReadToEnd()); responseReader.Close(); } response.Close(); } return jsonResponse; }
/// <summary> /// 获取远程文件大小 /// </summary> /// <param name="sURL"></param> /// <returns></returns> public static long GetRemoteHTTPFileSize(string sURL) { long size = 0L; try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(sURL); request.Method = "HEAD"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); size = response.ContentLength; response.Close(); } catch { size = 0L; } return(size); }
/// <summary> /// Gets the text response. /// </summary> /// <param name="response">The response.</param> /// <returns>System.String.</returns> public static string GetTextResponse(HttpWebResponse response) { string textResponse = null; if (response == null) return null; using (response) { // ReSharper disable once AssignNullToNotNullAttribute using (var responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { textResponse = responseReader.ReadToEnd(); responseReader.Close(); } response.Close(); } return textResponse; }
/// <summary> /// Download the specified text page. /// </summary> /// <param name="response">The HttpWebResponse to download from.</param> /// <param name="filename">The local file to save to.</param> public void DownloadBinaryFile(HttpWebResponse response, String filename) { byte[] buffer = new byte[4096]; FileStream os = new FileStream(filename, FileMode.Create); Stream stream = response.GetResponseStream(); int count = 0; do { count = stream.Read(buffer, 0, buffer.Length); if (count > 0) os.Write(buffer, 0, count); } while (count > 0); response.Close(); stream.Close(); os.Close(); }
public void LoginPsn(Common.Login login) { //var getData = new Dictionary<string, string>(); //getData.Add("request_locale", "en_US"); //getData.Add("service-entity", "psn"); //getData.Add("returnURL", _loginReturnUrl); //var loginSource = GetSourceCode(_loginUrl, getData: getData); //var htmlDocument = new HtmlDocument(); //htmlDocument.LoadHtml(loginSource); //var strutsTokenName = htmlDocument.DocumentNode.SelectSingleNode("//input[@name='struts.token.name']").Attributes["value"].Value; //var strutsToken = htmlDocument.DocumentNode.SelectSingleNode("//input[@name='struts.token']").Attributes["value"].Value; var postData = new Dictionary <string, string>(); //postData.Add("struts.token.name", strutsTokenName); //postData.Add("struts.token", strutsToken); postData.Add("j_username", login.Username); //postData.Add("rememberSignIn", "on"); postData.Add("j_password", login.Password); //postData.Add("service-entity", "psn"); using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)CreateHttpWebRequest(_loginUrl, postData: postData).GetResponse()) { if (httpWebResponse.Cookies["JSESSIONID"] == null) { throw new InvalidCredentialsException(); } _sessionId = httpWebResponse.Cookies["JSESSIONID"].Value; httpWebResponse.Close(); } var ticketUrl = string.Format(_ticketUrl, _sessionId); using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)CreateHttpWebRequest(ticketUrl).GetResponse()) { httpWebResponse.Close(); } }
private void button3_Click(object sender, EventArgs e) { string url = textBox1.Text; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { Stream receiveStream = response.GetResponseStream(); StreamReader readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); string data = readStream.ReadToEnd(); richTextBox1.Text = data; String result = Regex.Replace(data, @"<.*?>", String.Empty); richTextBox2.Text = WebUtility.HtmlDecode(result); response.Close(); readStream.Close(); } }
public static object GetJsonResponse(HttpWebResponse response) { object JsonResponse = null; if (response != null) { using (response) { using (StreamReader ResponseReader = new StreamReader(response.GetResponseStream())) { JsonResponse = JsonConvert.DeserializeObject(ResponseReader.ReadToEnd()); ResponseReader.Close(); } response.Close(); } } return JsonResponse; }
public static string GetTextResponse(HttpWebResponse response) { string TextResponse = null; if (response != null) { using (response) { using (StreamReader ResponseReader = new StreamReader(response.GetResponseStream(), ASCIIEncoding.UTF8)) { TextResponse = ResponseReader.ReadToEnd(); ResponseReader.Close(); } response.Close(); } } return TextResponse; }
public CimomResponse(HttpWebResponse nHttpResp) { httpResp = nHttpResp; statusCode = httpResp.StatusCode; statusDescription = httpResp.StatusDescription; StreamReader streamRead = new StreamReader(httpResp.GetResponseStream(), System.Text.UTF8Encoding.UTF8); message = streamRead.ReadToEnd(); streamRead.Close(); // Release the HttpResponse Resource. httpResp.Close(); if (OnCimomResponse != null) { OnCimomResponse((int)this.StatusCode, Message); } }
public static string GetStocksHttpRequest(string strURL, IDictionary <string, string> parameters) { // 创建一个HTTP请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL); //http请求 System.Net.HttpWebResponse httpWebResponse = CreatePostHttpResponse(strURL, parameters, 10000, null, null); if (httpWebResponse == null) { return("RequestFailed.aspx?result=出错了,可能是由于您的网络环境差、不稳定或安全软件禁止访问网络,您可在网络好时或关闭安全软件在重新访问网络。"); } else { //获取返回数据转为字符串 string jsonString = GetResponseString(httpWebResponse); httpWebResponse.Close(); return(jsonString); } }
public Proxy(ProxyConfig _pxc) { pxc = _pxc; System.Diagnostics.Trace.WriteLine("Starting Lawmate gateway..."); ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; System.Uri u = new Uri(pxc.serverR.remoteUrl);// + "/"); cc = new System.Net.CredentialCache(); if (pxc.user.Contains("\\")) { cc.Add(u, "Negotiate", CredentialCache.DefaultNetworkCredentials); } else { System.Net.NetworkCredential nc = new System.Net.NetworkCredential(pxc.user, pxc.password); cc.Add(u, "Digest", nc); cc.Add(u, "Basic", nc); } System.Net.HttpWebRequest wcinit = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(u); jar = new CookieContainer(); wcinit.CookieContainer = jar; wcinit.Credentials = cc; wcinit.PreAuthenticate = true; wcinit.UnsafeAuthenticatedConnectionSharing = true; //for kerberos try { System.Net.HttpWebResponse hwinit = (System.Net.HttpWebResponse)wcinit.GetResponse(); hwinit.Close(); System.Diagnostics.Trace.WriteLine("Ready to start Lawmate..."); } catch (Exception x) { System.Diagnostics.Trace.WriteLine(x.Message); return; } }
/// <summary> /// Gets the response from the web request /// </summary> /// <param name="uri">URI to request</param> /// <param name="response">Returned response</param> /// <returns>Response string</returns> private string GetFinalResponse(string uri, out HttpWebResponse response) { HttpWebRequest request = this.CreateWebRequest(uri, "GET"); try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException wex) { response = (HttpWebResponse)wex.Response; return wex.Message; } StreamReader stream = new StreamReader(response.GetResponseStream()); string responseString = stream.ReadToEnd(); stream.Close(); response.Close(); return responseString; }
private void OnNewCall(object sender, TapiCallNotificationEventArgs e) { if (e.Call.Privilege == CALL_PRIVILEGE.CP_OWNER) { //lbCalls.Items.Add(e.Call); lbRing.Text = e.Call.get_CallInfo(CALLINFO_STRING.CIS_CALLERIDNUMBER); } lbRing.BackColor = Color.FromArgb(0, 255, 0); this.BackColor = Color.FromArgb(0, 255, 0); this.LogWrite(sURL + lbRing.Text); if (lbRing.Text != "") { try { // Create a new 'HttpWebRequest' Object to the mentioned URL. System.Net.HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(sURL + lbRing.Text); myHttpWebRequest.Timeout = 10000; myHttpWebRequest.ReadWriteTimeout = 10000; myHttpWebRequest.KeepAlive = false; myHttpWebRequest.ProtocolVersion = HttpVersion.Version11; myHttpWebRequest.Method = "GET"; System.Net.HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); myHttpWebResponse.Close(); myHttpWebResponse = null; myHttpWebRequest = null; //System.Net.WebRequest req = System.Net.WebRequest.Create(sURL + lbRing.Text); //System.Net.WebResponse resp = req.GetResponse(); } catch (Exception err) { lbRing.BackColor = Color.FromArgb(255, 0, 0); this.BackColor = Color.FromArgb(255, 0, 0); tbLog.Text = err.ToString(); this.LogWrite(err.ToString()); } } else { this.LogWrite("No number ?!"); } }
public void SkiniDatoteku(string sUrlToDnldFile, string sFileSavePath) { try { Uri url = new Uri(sUrlToDnldFile); string sFileName = Path.GetFileName(url.LocalPath); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); long iSize = response.ContentLength; long iRunningByteTotal = 0; WebClient client = new WebClient(); Stream strRemote = client.OpenRead(url); FileStream strLocal = new FileStream(sFileSavePath, FileMode.Create, FileAccess.Write, FileShare.None); int iByteSize = 0; byte[] byteBuffer = new byte[1024]; while ((iByteSize = strRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { strLocal.Write(byteBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; double dIndex = (double)(iRunningByteTotal); double dTotal = (double)iSize; double dProgressPercentage = (dIndex / dTotal); int iProgressPercentage = (int)(dProgressPercentage * 100); } strRemote.Close(); } catch (Exception exM) { MessageBox.Show("Error: " + exM.Message); } }
private static Boolean OutDatedPdv() { try { string address = "https://dmiautomacao.000webhostapp.com/Pdv.zip"; System.Net.HttpWebRequest pdvfile = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(address); System.Net.HttpWebResponse pdvFileResponse = (System.Net.HttpWebResponse)pdvfile.GetResponse(); pdvFileResponse.Close(); string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "Pdv.zip"; DateTime localFileModifiedTime = File.GetLastWriteTime(path); DateTime onlineFileModifiedTime = pdvFileResponse.LastModified; return(localFileModifiedTime >= onlineFileModifiedTime ? false : true); } catch (WebException e) { MessageBox.Show("Erro Ocorrido:\n " + e.Message + "\nStatus: " + e.Status); return(false); } }
private static string GetHtml(int appId, HttpWebResponse response) { if (response.StatusCode != HttpStatusCode.OK) throw new InvalidAppException(appId); using (var receiveStream = response.GetResponseStream()) { if (receiveStream == null) throw new InvalidAppException(appId); var readStream = response.CharacterSet == null ? new StreamReader(receiveStream) : new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); var data = readStream.ReadToEnd(); response.Close(); readStream.Close(); return data; } }
public static string GetHTML(string theURL) { string someHtml = null; // *** Establish the request &INTERNAL=Y added to querystring so WebComm knows it's an application request and not a client navigation System.Net.HttpWebRequest objHttp = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(theURL); objHttp.Timeout = 100000; // timeout 100 sec // *** Retrieve request info headers System.Net.HttpWebResponse oWebResponse = (System.Net.HttpWebResponse)objHttp.GetResponse(); System.Text.Encoding enc = System.Text.Encoding.GetEncoding(1252); System.IO.StreamReader oResponseStream = new System.IO.StreamReader(oWebResponse.GetResponseStream(), enc); someHtml = oResponseStream.ReadToEnd(); //get html as string oWebResponse.Close(); oResponseStream.Close(); return(someHtml); }
/// <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 string WebPagePostGet(string url, string data, string charset) { 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; if (charset == "gb2312") { coding = System.Text.Encoding.GetEncoding("gb2312"); } else { coding = System.Text.Encoding.UTF8; } 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> /// 检查代理ip是否可用 /// </summary> /// <param name="proxyIp"></param> /// <returns></returns> static bool CheckProxyIp(string proxyIp) { if (string.IsNullOrEmpty(proxyIp)) { return(false); } proxyIp = proxyIp.ToLower().Replace("http://", ""); if (string.IsNullOrEmpty(proxyIp)) { return(false); } proxyIp = "http://" + proxyIp; int 网络异常重试次数 = 0; begin: try { WebProxy wp = new WebProxy(new Uri(proxyIp)); HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri("http://www.baidu.com", false)); request.Proxy = wp; request.Method = "get"; request.Timeout = 3000; request.AllowAutoRedirect = true; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); } catch (Exception ex) { //网络异常重试次数++; //if (网络异常重试次数 < 3) //{ // System.Threading.Thread.Sleep(1600); // goto begin; //} return(false); } return(true); }
/// <summary> /// 从uc.qbox.me查询得到回复后,解析出upHost,然后根据upHost确定Zone /// </summary> /// <param name="accessKey">AK</param> /// <param name="bucketName">Bucket</param> public static ZoneID Query(string accessKey, string bucketName) { ZoneID zoneId = ZoneID.Default; // HTTP/GET https://uc.qbox.me/v1/query?ak=(AK)&bucket=(Bucket) // 该请求的返回数据参见后面的 QueryResponse 结构 // 根据response消息提取出upHost string query = string.Format("https://uc.qbox.me/v1/query?ak={0}&bucket={1}", accessKey, bucketName); //不同区域upHost分别唯一,据此确定对应的Zone Dictionary <string, ZoneID> ZONE_DICT = new Dictionary <string, ZoneID>() { { "http://up.qiniu.com", ZoneID.CN_East }, { "http://up-z1.qiniu.com", ZoneID.CN_North }, { "http://up-z2.qiniu.com", ZoneID.CN_South }, { "http://up-na0.qiniu.com", ZoneID.US_North } }; try { HttpWebRequest wReq = WebRequest.Create(query) as HttpWebRequest; wReq.Method = "GET"; System.Net.HttpWebResponse wResp = wReq.GetResponse() as System.Net.HttpWebResponse; using (StreamReader sr = new StreamReader(wResp.GetResponseStream())) { string respData = sr.ReadToEnd(); QueryResponse qr = Newtonsoft.Json.JsonConvert.DeserializeObject <QueryResponse>(respData); string upHost = qr.HTTP.UP[0]; zoneId = ZONE_DICT[upHost]; } wResp.Close(); } catch (Exception ex) { throw new Exception("ConfigZone:" + ex.Message); } return(zoneId); }
public HttpPost(Uri url, Dictionary<string, string> parameters) { var respBody = new StringBuilder(); _request = (HttpWebRequest)WebRequest.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.Method = "POST"; _request.ContentType = "application/x-www-form-urlencoded"; var content = parameters.Keys.Aggregate("?", (current, k) => current + (k + "=" + parameters[k] + "&")); content = content.TrimEnd(new[] { '&' }); var encoding = new UTF8Encoding(); var byteArr = encoding.GetBytes(content); _request.ContentLength = byteArr.Length; var buf = new byte[8192]; using (Stream rs = _request.GetRequestStream()) { rs.Write(byteArr, 0, byteArr.Length); rs.Close(); _response = (HttpWebResponse)_request.GetResponse(); Stream respStream = _response.GetResponseStream(); var count = 0; do { if (respStream != null) count = respStream.Read(buf, 0, buf.Length); if (count != 0) respBody.Append(Encoding.ASCII.GetString(buf, 0, count)); } while (count > 0); if (respStream != null) respStream.Close(); ResponseBody = respBody.ToString(); _escapedBody = GetEscapedBody(); StatusCode = GetStatusLine(); Headers = GetHeaders(); _response.Close(); } }
// 使用 Media.SoundPlayer 播放 Http 请求的 wav 文件流 // 使用同步播放,播放完后才返回 private static Stream HttpPostRequestGetStream(string url) { try { if (!string.IsNullOrEmpty(url)) { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); req.Timeout = 5000; req.Method = "POST"; System.Net.HttpWebResponse rsp = (System.Net.HttpWebResponse)req.GetResponse(); if (rsp?.ContentLength > 0) { MemoryStream memStream; using (Stream response = rsp.GetResponseStream()) { memStream = new MemoryStream(); byte[] buffer = new byte[1024]; int byteCount; do { byteCount = response.Read(buffer, 0, buffer.Length); memStream.Write(buffer, 0, byteCount); } while (byteCount > 0); } memStream.Seek(0, SeekOrigin.Begin); rsp.Close(); return(memStream); } } } catch (Exception e1) { System.Diagnostics.Debug.WriteLine("Speakers HttpPostRequestGetStream," + e1.Message.ToString()); } return(null); }
/// <summary> /// 根据页面url获取页面html字符 /// </summary> /// <param name="url">页面url</param> /// <param name="encoding">页面编码</param> /// <returns></returns> public static string GetHtml(string url, string encoding) { WebProxy wp = new WebProxy(); string resultHtml = ""; HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url, false)); request.Method = "get"; request.Timeout = 10000; request.KeepAlive = false; request.AllowAutoRedirect = true; request.ContentType = "application/x-www-form-urlencoded"; request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; CookieContainer cc = new CookieContainer(); request.CookieContainer = cc; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); if (response.Headers["Content-Encoding"] == "gzip") //gzip解压处理 { MemoryStream msTemp = new MemoryStream(); GZipStream gzs = new GZipStream(stream, CompressionMode.Decompress); byte[] buf = new byte[1024]; int len; while ((len = gzs.Read(buf, 0, buf.Length)) > 0) { msTemp.Write(buf, 0, len); } msTemp.Position = 0; stream = msTemp; } System.IO.StreamReader read = new System.IO.StreamReader(stream, Encoding.GetEncoding(encoding)); resultHtml = read.ReadToEnd(); response.Close(); return(resultHtml); }
public static long GetPlusOnes(string url) { try { 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); } catch (Exception) { return(0); } }
private string GetResponseContent(HttpWebResponse response) { if (response == null) { return null; } Stream dataStream = null; StreamReader reader = null; string responseFromServer = null; try { // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. reader = new StreamReader(dataStream); // Read the content. responseFromServer = reader.ReadToEnd(); // Cleanup the streams and the response. } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (reader != null) { reader.Close(); } if (dataStream != null) { dataStream.Close(); } response.Close(); } return responseFromServer; }
public HttpResponse Create(HttpWebResponse response) { var statusCode = response.StatusCode; var statusDescription = response.StatusDescription; Stream dataStream = null; StreamReader responseStream = null; try { dataStream = response.GetResponseStream(); responseStream = new StreamReader(dataStream); var content = responseStream.ReadToEnd(); return new HttpResponse(statusCode, statusDescription, content); } finally { new SuppressExceptions().On(() => responseStream.Close()); new SuppressExceptions().On(() => dataStream.Close()); new SuppressExceptions().On(() => response.Close()); } }
public void BuildHtml(string nameId) { //WebRequest // Create a request for the URL. System.Net.WebRequest request = System.Net.WebRequest.Create("http://" + Request.ServerVariables["Http_Host"] + "/app/ShowGameHtml.aspx?id=" + nameId); request.Timeout = 10000; //毫秒 // If required by the server, set the credentials. request.Credentials = System.Net.CredentialCache.DefaultCredentials; // Get the response. System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); // string charset = response.CharacterSet; // Get the stream containing content returned by the server. System.IO.Stream dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. System.Text.Encoding encode = System.Text.Encoding.GetEncoding(charset); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream, encode); //获取文件路径 string FILE_NAME = Server.MapPath("/Html/GameInfo/" + nameId + ".html"); if (System.IO.File.Exists(FILE_NAME)) { System.IO.File.Delete(FILE_NAME); } //Read the content,把文件保存到网站指定的目录下 System.IO.File.WriteAllText(FILE_NAME, reader.ReadToEnd(), encode); // Cleanup the streams and the response. reader.Close(); dataStream.Close(); response.Close(); }
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 string SendSMS(string PostData) { string Result = string.Empty; #region 发送 接收 try { byte[] SendBytes = Encoding.UTF8.GetBytes(PostData); System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create("http://115.29.206.137:8081/myservice.asmx/SendSMS") as System.Net.HttpWebRequest; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = SendBytes.Length; using (System.IO.Stream newStream = request.GetRequestStream()) { newStream.Write(SendBytes, 0, SendBytes.Length); newStream.Close(); } using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse()) { using (System.IO.StreamReader readStream = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8)) { Result = readStream.ReadToEnd(); readStream.Close(); readStream.Dispose(); } response.Close(); } } catch { } #endregion return(Result); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { try { string count = "count=" + Microsoft.VisualBasic.Interaction.InputBox("Please enter the max number of servers to retrieve", "Number of servers", "", 100, 100); string filter = Microsoft.VisualBasic.Interaction.InputBox("Please enter whatever dvar you want filtered.\ndvar=filter, seperate with \\", "Filter", "", 100, 100); string uri = "http://server.alteriw.net:13000/servers/yeQA4reD/" + filter + @"/" + count + ".xml"; string file = "servers.xml"; // first, we need to get the exact size (in bytes) of the file we are downloading Uri url = new Uri(uri); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); // gets the size of the file in bytes Int64 iSize = response.ContentLength; // keeps track of the total bytes downloaded so we can update the progress bar Int64 iRunningByteTotal = 0; // use the webclient object to download the file using (System.Net.WebClient client = new System.Net.WebClient()) { // open the file at the remote URL for reading using (System.IO.Stream streamRemote = client.OpenRead(new Uri(uri))) { // using the FileStream object, we can write the downloaded bytes to the file system using (Stream streamLocal = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None)) { // loop the stream and get the file into the byte buffer int iByteSize = 0; byte[] byteBuffer = new byte[iSize]; while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // write the bytes to the file system at the file path specified streamLocal.Write(byteBuffer, 0, iByteSize); iRunningByteTotal += iByteSize; // calculate the progress out of a base "100" double dIndex = (double)(iRunningByteTotal); double dTotal = (double)byteBuffer.Length; double dProgressPercentage = (dIndex / dTotal); int iProgressPercentage = (int)(dProgressPercentage * 100); // update the progress bar backgroundWorker1.ReportProgress(iProgressPercentage); } // clean up the file stream streamLocal.Close(); } // close the connection to the remote server streamRemote.Close(); } } } catch (Exception asdsa) { MessageBox.Show("ERROR\n" + asdsa); } }
public static string GetResponseContent(HttpWebResponse response) { if (response == null) { throw new ArgumentNullException("response"); } Stream dataStream = null; StreamReader reader = null; string responseFromServer; try { dataStream = response.GetResponseStream(); reader = new StreamReader(dataStream); responseFromServer = reader.ReadToEnd(); } finally { if (reader != null) { reader.Close(); } if (dataStream != null) { dataStream.Close(); } response.Close(); } return responseFromServer; }