/// <summary> /// 读取页面内容 /// </summary> /// <param name="url"></param> /// <param name="encodingType"></param> /// <returns></returns> public static string ReadPageContentByUrl(string url, string encodingType) { try { StringBuilder dataReturnString = new StringBuilder(); Stream dataStream; 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) { dataStream = resp.GetResponseStream(); System.Text.Encoding encode = System.Text.Encoding.GetEncoding(encodingType); StreamReader readStream = new StreamReader(dataStream, encode); char[] cCount = new char[500]; int count = readStream.Read(cCount, 0, 256); while (count > 0) { String str = new String(cCount, 0, count); dataReturnString.Append(str); count = readStream.Read(cCount, 0, 256); } resp.Close(); return(dataReturnString.ToString()); } resp.Close(); return(null); } catch { return("网络异常...请稍后再试。"); } }
/// <summary> /// 向服务器 POST 数据 /// </summary> /// <param name="result">接收返回内容</param> /// <param name="postUrl">服务器地址</param> /// <param name="paramData">数据(eg: "键=值&name=Kity",注意值部份需用 string System.Web.HttpUtility.UrlPathEncode(string) 进行编码)</param> /// <param name="dataEncode">参数编码(eg: System.Text.Encoding.UTF8)</param> /// <returns>请求成功则用服务器返回内容填充result, 否则用异常消息填充</returns> public static bool PostWebRequest(out string result, string postUrl, string paramData, System.Text.Encoding dataEncode) { try { byte[] byteArray = dataEncode.GetBytes(paramData); //转化 System.Net.HttpWebRequest webReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(postUrl)); //webReq.ProtocolVersion = new Version("1.0"); //webReq.UserAgent = ""; //webReq.CookieContainer = new System.Net.CookieContainer(); webReq.Method = "POST"; webReq.ContentType = "application/x-www-form-urlencoded"; webReq.ContentLength = byteArray.Length; System.IO.Stream newStream = webReq.GetRequestStream(); newStream.Write(byteArray, 0, byteArray.Length); newStream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)webReq.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), dataEncode); result = sr.ReadToEnd(); sr.Close(); response.Close(); newStream.Close(); } catch (Exception ex) { result = ex.Message; return(false); } return(true); }
public void TestCreateDownloadLink() { var assetStorageProvider = GetAssetStorageProvider(); var s3Component = assetStorageProvider.GetAssetStorageComponent(); Asset asset = new Asset(); asset.Type = AssetType.File; asset.Key = "UnitTestFolder/SubFolder1/TestUploadObjectByName.jpg"; string url = s3Component.CreateDownloadLink(assetStorageProvider, asset); bool valid = false; try { System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; request.Method = "GET"; System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse; response.Close(); valid = response.StatusCode == System.Net.HttpStatusCode.OK ? true : false; } catch { valid = false; } Assert.True(valid); }
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="charset">网页编码</param> /// <returns></returns> public static string WebPageContentGet(string url, string charset) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); 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); }
public static string GetUrltoHtml(string Url, string type = "UTF-8") { try { System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(Url); r.AllowAutoRedirect = true; r.KeepAlive = false; r.ServicePoint.Expect100Continue = false; r.ServicePoint.UseNagleAlgorithm = false; r.ServicePoint.ConnectionLimit = 65500; r.AllowWriteStreamBuffering = false; r.Proxy = null; System.Net.CookieContainer c = new System.Net.CookieContainer(); r.CookieContainer = c; System.Net.HttpWebResponse res = r.GetResponse() as System.Net.HttpWebResponse; System.IO.StreamReader s = new System.IO.StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding(type)); string retsult = s.ReadToEnd(); res.Close(); r.Abort(); return(retsult); } catch (System.Exception ex) { //errorMsg = ex.Message; return(ex.Message); } }
/// <summary> /// 下载单个文件 /// </summary> /// <param name="url">下载链接地址</param> /// <param name="path">相对路径</param> /// <param name="filename">文件名</param> /// <param name="temppath">本地临时文件夹</param> public static void DownLoadSingleFile(string url, string path, string filename, string temppath) { string downloadurl = url + "?action=GetSingleFile&path=" + path + "&filename=" + filename; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(downloadurl); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); long totalBytes = myrp.ContentLength; System.IO.Stream st = myrp.GetResponseStream(); string localname = temppath + path + filename; System.IO.Stream so = new System.IO.FileStream(localname, 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; so.Write(by, 0, osize); osize = st.Read(by, 0, (int)by.Length); } so.Close(); st.Close(); myrp.Close(); Myrq.Abort(); } catch (Exception ex) { throw ex; } }
private dynamic GetJsonResult(string url, string postData) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); if (!string.IsNullOrEmpty(postData)) { 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(); if (responseStream != null) { System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8); var jsonString = readStream.ReadToEnd(); readStream.Close(); responseStream.Close(); response.Close(); var json = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize <dynamic>(jsonString); return(json); } return(null); }
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(); string s = readStream.ReadLine(); response.Close(); //if (ValidateFile(s)) { rv = s; } } catch (Exception) { // Anything could have happened here but // we don't want to stop the user // from using the application. rv = null; } return(rv); }
/// <summary> /// Write something about the response to the Log and raise some exceptions if the upload failed. /// </summary> /// <param name="response">The WebResponse</param> private void HandleResponse(System.Net.HttpWebResponse response) { using (var reader = new StreamReader(response.GetResponseStream())) { Log.Instance.Write("### Begin of response ##########################" + Environment.NewLine + reader.ReadToEnd().Replace("\n", "\r\n")); Log.Instance.Write("### End of response ##########################"); } switch (response.StatusCode) { case System.Net.HttpStatusCode.OK: Log.Instance.Write("Upload successfull!"); break; case System.Net.HttpStatusCode.PartialContent: Log.Instance.Write("Upload finished with warnings."); break; case System.Net.HttpStatusCode.Unauthorized: Log.Instance.Write("Not Authorized!"); throw new NotAuthorizedException(); default: Log.Instance.Write("Upload failed!"); throw new UploadFailedException(); } response.Close(); }
/// <summary> /// http://dobon.net/vb/dotnet/internet/detectinternetconnect.html /// </summary> /// <returns></returns> private static bool IsInternetConnected() { //インターネットに接続されているか確認する 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(); //応答ステータスコードを表示 //Console.WriteLine(webres.StatusCode); return(true); } catch { return(false); } finally { if (webres != null) { webres.Close(); } } }
bool url_endpoint_exists(string p_target_server, string p_user_name, string p_password, string p_method = "HEAD") { System.Net.HttpStatusCode response_result; try { //Creating the HttpWebRequest System.Net.HttpWebRequest request = System.Net.WebRequest.Create(p_target_server) as System.Net.HttpWebRequest; //Setting the Request method HEAD, you can also use GET too. request.Method = p_method; if (!string.IsNullOrWhiteSpace(p_user_name) && !string.IsNullOrWhiteSpace(p_password)) { string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(p_user_name + ":" + p_password)); request.Headers.Add("Authorization", "Basic " + encoded); } //Getting the Web Response. System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse; //Returns TRUE if the Status code == 200 response_result = response.StatusCode; response.Close(); return(response_result == System.Net.HttpStatusCode.OK); } catch (Exception ex) { //Log.Information ($"failed end_point exists check: {p_target_server}\n{ex}"); Console.WriteLine($"failed end_point exists check: {p_target_server}"); return(false); } }
private bool DownloadFile(string URL, string filename) { try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); Myrq.Timeout = 5000; Myrq.ReadWriteTimeout = 5000; System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); 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 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); } catch (System.Exception e) { return(false); } }
public bool DownloadWithURL(string sUrl, string sSave) { try {// Xác định dung lượng tập tin Uri url = new Uri(sUrl); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); response.Close(); // Lấy dung lượng tập tin Int64 iSize = response.ContentLength; // Dùng Webclient để download System.Net.WebClient client = new System.Net.WebClient(); // Mở URL để download Stream streamRemote = client.OpenRead(new Uri(sUrl)); // Vừa đọc vừa lưu Stream streamLocal = new FileStream(sSave, FileMode.Create, FileAccess.Write, FileShare.None); // Tiến hành loop quá trình download, vừa load vừa lưu int iByteSize = 0; byte[] byteBuffer = new byte[iSize]; while ((iByteSize = streamRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0) { // Lưu byte xuống đường dẫn chỉ định streamLocal.Write(byteBuffer, 0, iByteSize); } streamLocal.Close(); streamRemote.Close(); return(true); } catch (Exception) { return(false); } }
public static string GetWanIP(string url) { //http://www.ip138.com/ip2city.asp Uri uri = new Uri(url); 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(); //s = "116.10.175.142"; System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, @"(\d+)\.(\d+)\.(\d+)\.(\d+)"); if (m.Success) { return(m.Value); } return(string.Empty); }
public FileContentResult DownQRCode(string url) { string qrUrl = $"http://chart.apis.google.com/chart?cht=qr&chl={ Server.UrlEncode(url) }&chs=170x170&choe=UTF-8"; System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(qrUrl); req.ServicePoint.Expect100Continue = false; req.KeepAlive = true; req.Method = "GET"; req.ContentType = "image/png"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)req.GetResponse(); System.IO.Stream stream = null; System.IO.MemoryStream memoryStream = null; try { stream = response.GetResponseStream(); System.Drawing.Image bitmap = System.Drawing.Image.FromStream(stream); memoryStream = new System.IO.MemoryStream(); bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png); return(File(memoryStream.ToArray(), "application/octet-stream", "QRCode.png")); } finally { if (memoryStream != null) { memoryStream.Close(); } if (stream != null) { stream.Close(); } if (response != null) { response.Close(); } } }
private static bool openUrlDownloadFile(Log4netUtil.LogAppendToForms logAppendToForms, string url, string filename, bool isDebug) { try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); 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 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); } catch (Exception ex) { string logMessage = string.Format("【随货同行下载任务】 Url {0} 下载失败!原因,{1}", url, ex.Message); Log4netUtil.Log4NetHelper.LogMessage(logAppendToForms, isDebug, logMessage, @"Util\FileHelper"); return(false); } }
public bool http_test() { try { string website_address; website_address = "http://www.google.com/"; System.Net.WebRequest myWebrequest = System.Net.WebRequest.Create(website_address); myWebrequest.Timeout = 3000; resp = (System.Net.HttpWebResponse)myWebrequest.GetResponse(); if (resp.StatusCode.ToString().Equals("OK")) { return(true); } else { MessageBox.Show("Connecting to the internet failed , please check your internet connection or the website " + website_address); return(false); } } catch { return(false); } finally { if (resp != null) { resp.Close(); } } }
/// <summary> /// Downloads the page /// </summary> /// <param name="uri"></param> /// <returns></returns> public bool DownloadPage() { bool success = false; // Open the requested URL string unescapedUri = Regex.Replace(PageToRetrieve.AbsoluteUri, @"&amp;", @"&", RegexOptions.IgnoreCase); System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(unescapedUri); req.AllowAutoRedirect = true; req.MaximumAutomaticRedirections = 3; req.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; RetrEave.Com; robot)"; req.KeepAlive = true; req.Timeout = 5 * 1000; // Get the stream from the returned web response System.Net.HttpWebResponse webresponse = null; try { webresponse = (System.Net.HttpWebResponse)req.GetResponse(); } catch (System.Net.WebException we) { //remote url not found, 404; remote url forbidden, 403 //TODO do something here, like log it? } if (webresponse != null) { success = GetResponse(webresponse); webresponse.Close(); } return(success); }
/// <summary> /// 打开网址并下载文件 /// </summary> /// <param name="URL">下载文件地址</param> /// <param name="Filename">下载后另存为(全路径)</param> private static bool OpenUrlDownloadFile(Log4netUtil.LogAppendToForms logAppendToForms, Model.JobEntity jobInfo, 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(); 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 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); } catch (Exception ex) { string logMessage = string.Format("【{0}_{1}】 下载文件失败 ;原因:{2}", jobInfo.JobCode, jobInfo.JobName, ex.Message); Log4netUtil.Log4NetHelper.LogError(logAppendToForms, true, logMessage, @"Ftp"); return(false); } }
public void accessCheck(String url) { String access_url = null; String[] access_code = new String[2]; //URIの有効性の確認 Uri uriResult; bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); if (result) { //WebRequestの作成 System.Net.HttpWebRequest webreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse webres = null; try { //サーバーからの応答を受信するためのWebResponseを取得 webres = (System.Net.HttpWebResponse)webreq.GetResponse(); //応答したURIを表示する access_url = webres.ResponseUri.ToString(); //応答ステータスコードを表示する access_code[0] = webres.StatusCode.ToString(); Console.WriteLine(webres.StatusCode + ", " + webres.StatusDescription); access_code[1] = webres.StatusDescription; } catch (System.Net.WebException ex) { //HTTPプロトコルエラーかどうか調べる if (ex.Status == System.Net.WebExceptionStatus.ProtocolError) { //HttpWebResponseを取得 System.Net.HttpWebResponse errres = (System.Net.HttpWebResponse)ex.Response; //応答したURIを表示する access_url = errres.ResponseUri.ToString(); //応答ステータスコードを表示する access_code[0] = errres.StatusCode.ToString(); access_code[1] = errres.StatusDescription; } } finally { //閉じる if (webres != null) { webres.Close(); } } MessageBox.Show("接続URL: " + access_url + "\n" + "HTTPステータス: " + access_code[0] + " " + access_code[1], "HTTP接続結果", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("有効なURLではありません。", "確認してください", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void x(string sUrlToReadFileFrom) { int iLastIndex = sUrlToReadFileFrom.LastIndexOf('/'); string sDownloadFileName = sUrlToReadFileFrom.Substring(iLastIndex + 1, (sUrlToReadFileFrom.Length - iLastIndex - 1)); string sFilePathToWriteFileTo = location + "\\" + sDownloadFileName; // first, we need to get the exact size (in bytes) of the file we are downloading Uri url = new Uri(sUrlToReadFileFrom); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); 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(sUrlToReadFileFrom))) { // using the FileStream object, we can write the downloaded bytes to the file system using (Stream streamLocal = new FileStream(sFilePathToWriteFileTo, 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) { if (backgroundWorker1.CancellationPending) { break; } // 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(); } } }
/// <summary> /// api jspon 결과값을 가져오기 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="method"></param> /// <returns></returns> public string Get_Sync_Api(string url, string data, web_method method) { try { url = url.Trim(); url = _c_s_api_url + (url.StartsWith("/") ? "" : "/") + url; byte[] postData = Encoding.Default.GetBytes(data.ToString()); switch (method) { case web_method.GET: url = url + (url.EndsWith("?") || data.StartsWith("?") ? "" : "?") + data + "×tamp=" + System.DateTime.Now.ToFileTimeUtc().ToString(); break; } System.Text.StringBuilder sb_data = new StringBuilder(); System.Text.StringBuilder sb_result = new StringBuilder(); System.Net.HttpWebRequest wrq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); wrq.ContentType = "application/json"; wrq.Method = method.ToString(); if (method != web_method.GET) { wrq.ContentLength = postData.Length; System.IO.Stream newStream = wrq.GetRequestStream(); newStream.Write(postData, 0, postData.Length); newStream.Close(); } System.Net.HttpWebResponse wrs = (System.Net.HttpWebResponse)wrq.GetResponse(); System.IO.Stream strm = wrs.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(strm, Encoding.Default); string line; while ((line = sr.ReadLine()) != null) { sb_result.Append(line); } sr.Close(); strm.Close(); wrs.Close(); return(sb_result.ToString()); } catch (Exception ex) { string sRtn = @"{'timestamp':'{timestamp}','errorCode':'999999','result':'fail'}"; sRtn = sRtn.Replace("{timestamp}", System.DateTime.Now.ToFileTimeUtc().ToString()); return(sRtn); } }
/// <summary> /// 获取小区 /// </summary> /// <param name="row"></param> /// <returns></returns> public string GetCommunity(DataRow row) { string departId = ""; if (row.Table.Columns.Contains("departId")) { departId = row["departId"].ToString(); } string Url = UrlPrefix + "/mdserver/service/getCommunity"; System.Net.HttpWebResponse response = null; string resultstring = string.Empty; try { Encoding encoding = Encoding.GetEncoding("utf-8"); IDictionary <string, string> parameters = new Dictionary <string, string>(); parameters.Add("app_key", app_key); parameters.Add("agt_num", app_num); if (departId != "") { parameters.Add("departId", departId); } response = HttpHelper.CreatePostHttpResponse(Url, parameters, encoding); Stream stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream); resultstring = sr.ReadToEnd(); stream.Close(); sr.Close(); IDictionary <string, object> results = (IDictionary <string, object>)HttpHelper.JsonToDictionary(resultstring); if (results["status"].ToString() == "success") { resultstring = "{\"Result\":\"true\", \"data\": " + HttpHelper.SerializeToStr(results["data"]) + "}"; } else { resultstring = "{\"Result\":\"false\", \"data\": " + HttpHelper.SerializeToStr(results["msg"]) + "}"; } } catch (Exception exp) { resultstring = "{\"Result\":\"false\", \"data\": \"" + exp.ToString() + "\"}"; } finally { if (response != null) { response.Close(); } } return(resultstring); }
private bool SendRequest(String URL) { try { if (URL == null) { Trace.TraceWarning("URL is null."); return(false); } if (URL == String.Empty) { Trace.TraceWarning("URL is empty."); return(false); } System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL); request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_UCCXUsername + ":" + _UCCXPassword))); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, Encoding.UTF8); sResponse = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); streamReader = null; stream.Close(); stream.Dispose(); stream = null; response.Close(); response = null; request = null; return(true); } catch (System.Net.WebException webEx) { Trace.TraceWarning("WebException: " + webEx.Message + Environment.NewLine + "StackTrace: " + webEx.StackTrace + Environment.NewLine + "Status: " + webEx.Status); sResponse = String.Empty; return(false); } catch (Exception ex) { Trace.TraceWarning("Exception: " + ex.Message + Environment.NewLine + "StackTrace: " + ex.StackTrace); sResponse = String.Empty; return(false); } }
public void getlevels() { System.Net.HttpWebRequest myReg = (System.Net.HttpWebRequest) System.Net.WebRequest.Create("http://192.168.100.1/cgi-bin/status_cgi"); System.Net.HttpWebResponse myResp = (System.Net.HttpWebResponse)myReg.GetResponse(); Stream myStream = myResp.GetResponseStream(); StreamReader myReader = new StreamReader(myStream); int counter = 0; //Counter to count the index size of the list [0] string templine = myReader.ReadLine(); //Reads the first line int linecounter = 0; double dssnr = 0; while (!myReader.EndOfStream) { string regularExpressionPattern = @"<td>([^<]+)<\/td><td>(\d+)<\/td><td>([^<]+)<\/td><td>([^<]+)<\/td><td>([^<]+)<\/td>";//Before <td> we had <tr> Regex re = new Regex(regularExpressionPattern); foreach (Match m in re.Matches(templine)) { Console.WriteLine(m.Value); string result = Regex.Replace(m.Value, "((<td[^>]*>)|(</td>))", ""); //Between quotes we can put spacing if needed listBox1.Items.Add(templine); result = result.Substring(result.IndexOf('V') + 1); result = result.Replace(" dB", ""); if (linecounter < 8) // Sums all the downstream channels { double x = Double.Parse(result); dssnr = dssnr + x; } linecounter++; } Console.ReadLine(); counter++; lbllines.Text = counter.ToString(); //Print Num of lines templine = myReader.ReadLine(); } dssnr = dssnr / 8; //Calculate DDSNR (Divide downstream channel sum) double tempvalue = dssnr; textBox2.Text = dssnr.ToString(); textBox2.Text.Trim(); if (tempvalue > 35) { lblstatusdssnr.Text = " ✔"; } else if (tempvalue < 35) { lblstatusdssnr.Text = "HIGH DSSNR"; } myResp.Close(); get_upstream(); }
public void CreateDownloadLinkUsingNameShouldWorkCorrectly() { var assetStorageProvider = GetAssetStorageProvider(); var assetStorageComponent = assetStorageProvider.GetAssetStorageComponent(); var folderPath = $"/"; var filename = $"{Guid.NewGuid().ToString()}.jpg"; using (new HttpSimulator("/", webContentFolder).SimulateRequest()) { Asset expectedAsset = new Asset { Name = $"{folderPath}{filename}", AssetStream = new MemoryStream(_testJpgFileBytes), Type = AssetType.File }; bool hasUploaded = assetStorageComponent.UploadObject(assetStorageProvider, expectedAsset); Assert.That.IsTrue(hasUploaded); var actualAsset = assetStorageComponent.GetObject(assetStorageProvider, expectedAsset); Assert.That.IsNotNull(actualAsset); string url = assetStorageComponent.CreateDownloadLink(assetStorageProvider, expectedAsset); bool valid = false; try { System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; request.Method = "GET"; System.Net.HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse; response.Close(); valid = response.StatusCode == System.Net.HttpStatusCode.OK ? true : false; } catch (System.Net.WebException e) { using (System.Net.WebResponse response = e.Response) { System.Net.HttpWebResponse httpResponse = (System.Net.HttpWebResponse)response; if (httpResponse.StatusCode == System.Net.HttpStatusCode.Forbidden) { Assert.That.Inconclusive($"File ({expectedAsset.Key}) was forbidden from viewing."); } if (httpResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized) { Assert.That.Inconclusive($"Anonymous download is not allowed for ({expectedAsset.Key})."); } } } finally { assetStorageComponent.DeleteAsset(assetStorageProvider, actualAsset); } } }
private bool GetResponseFromServer() { try { String sURL = String.Empty; sURL = "http://" + _Settings.WebServerIP; if (_Settings.WebServerDataCollectionPort != String.Empty) { sURL = sURL + ":" + _Settings.WebServerDataCollectionPort; } String sToken = System.Text.RegularExpressions.Regex.Replace(_Settings.EncryptedUCCXAdminUser + _Settings.EncryptedUCCXAdminPassword, "[^A-Za-z0-9]", ""); sURL = sURL + "/uccxrealtimedata?operation=getcontactdata&token=" + sToken; //sURL = sURL + "/uccxrealtimedata?operation=getcontactdata&token=" + sToken + "&testing=true&numberofrecords=150&avgresponsedelay=5000"; Trace.TraceInformation("sURL = " + sURL); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(sURL); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); //Trace.TraceInformation("Content type is {0} and length is {1}", response.ContentType, response.ContentLength); System.IO.Stream stream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, Encoding.UTF8); sResponse = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); streamReader = null; stream.Close(); stream.Dispose(); stream = null; response.Close(); response = null; request = null; return(true); } catch (Exception ex) { Trace.TraceWarning("Exception: " + ex.Message + Environment.NewLine + "Stacktrace: " + ex.StackTrace); sResponse = String.Empty; return(false); } }
private static string GetHead(string remotefile, string localfile) { string sReturn = ""; try { System.IO.FileStream OutputBin = null; if (!string.IsNullOrEmpty(localfile)) { OutputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); } try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile); request.Method = "HEAD"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); byte[] buffer; string output; foreach (string sHeader in response.Headers) { output = sHeader + ":" + response.GetResponseHeader(sHeader); if (!string.IsNullOrEmpty(localfile)) { buffer = System.Text.Encoding.UTF8.GetBytes(output.ToCharArray()); OutputBin.Write(buffer, 0, buffer.Length); } else { Console.WriteLine(output); } } sReturn = response.StatusCode.ToString(); if (sReturn != response.StatusDescription) { sReturn += " " + response.StatusDescription; } response.Close(); } catch (Exception ex1) { sReturn = ex1.Message; } if (!string.IsNullOrEmpty(localfile)) { OutputBin.Close(); OutputBin.Dispose(); } } catch (Exception ex2) { sReturn = ex2.Message; } return(sReturn); }
private static string GetFile(string remotefile, string localfile) { string sReturn = ""; try { System.IO.FileStream OutputBin = null; if (!string.IsNullOrEmpty(localfile)) { OutputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); } try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile); request.Method = "GET"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream dataStream = response.GetResponseStream(); byte[] buffer = new byte[32768]; int read; while ((read = dataStream.Read(buffer, 0, buffer.Length)) > 0) { if (!string.IsNullOrEmpty(localfile)) { OutputBin.Write(buffer, 0, read); } else { Console.Write(System.Text.Encoding.UTF8.GetString(buffer).ToCharArray(), 0, read); } } dataStream.Close(); sReturn = response.StatusCode.ToString(); if (sReturn != response.StatusDescription) { sReturn += " " + response.StatusDescription; } response.Close(); } catch (Exception ex1) { sReturn = ex1.Message; } if (!string.IsNullOrEmpty(localfile)) { OutputBin.Close(); OutputBin.Dispose(); } } catch (Exception ex2) { sReturn = ex2.Message; } return(sReturn); }