//Allows for concurrent downloading of files //Allows for concurrent downloading of files private static async void downloadFile(QueuedFile nextFile) { testClient = new WebClient(); testClient.Proxy = GlobalProxySelection.GetEmptyWebProxy(); try { /**Stream stream = null; * HttpWebRequest ElementRequest = (HttpWebRequest)WebRequest.Create(nextFile.url); * ElementRequest.UserAgent = "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"; * ElementRequest.Referer = "http://google.com"; * HttpWebResponse HTMLResponse = (HttpWebResponse)ElementRequest.GetResponse(); * Stream streamResponse = HTMLResponse.GetResponseStream(); * //Downloads the image and saves it to the memorystream * stream = HTMLResponse.GetResponseStream(); * nextFile.stream = stream;**/ //Attempting to fix 403 error on many fullsize image loads byte[] testBytes = await testClient.DownloadDataTaskAsync(new Uri(nextFile.url)); nextFile.stream = new MemoryStream(testBytes); //ImageDisplay.printImage(stream); saveFile(nextFile); } catch (Exception e) { CU.WCol(CU.nl + "Could not download image at url " + nextFile.url + " : " + e + CU.nl, CU.r, CU.y); CU.WCol(CU.nl + e.StackTrace + CU.nl, CU.r, CU.y); } }
/// <summary> /// 获取指定文件大小 /// </summary> /// <param name="filename"></param> /// <returns></returns> public long GetFileSize(string filename) { FtpWebRequest reqFTP; long fileSize = 0; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename)); reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); //reqFTP.Proxy = WebRequest.DefaultWebProxy; reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy(); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + ex.Message); } return(fileSize); }
/// <summary> /// 删除文件 /// </summary> /// <param name="fileName"></param> public void Delete(string fileName) { try { string uri = ftpURI + fileName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty; //reqFTP.Proxy = WebRequest.DefaultWebProxy; reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy(); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { WriteTraceLog.Error("FtpWeb: Delete Error --> " + ex.Message + " 文件名:" + fileName); throw new Exception("FtpWeb: Delete Error --> " + ex.Message + " 文件名:" + fileName); } }
/// <summary> /// 删除文件夹 /// </summary> /// <param name="folderName"></param> public void RemoveDirectory(string folderName) { try { string uri = ftpURI + folderName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; //reqFTP.Proxy = WebRequest.DefaultWebProxy; reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy(); string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + folderName); } }
public void GetContextCallback(IAsyncResult result) { var context = listener.EndGetContext(result); listener.BeginGetContext(GetContextCallback, null); var request = context.Request; var response = context.Response; var url = request.Url; UriBuilder builder = new UriBuilder(url); builder.Port = url.Port == 8888 ? 80 : 443; url = builder.Uri; WebRequest webRequest = WebRequest.Create(url); webRequest.Proxy = GlobalProxySelection.GetEmptyWebProxy(); WebResponse webResponse = webRequest.GetResponse(); using (Stream reader = webResponse.GetResponseStream()) { using (Stream writer = response.OutputStream) { reader.CopyTo(writer); } } }
private string POST(string callName, string callPrefix, AlchemyAPI_BaseParams parameters) { // callMethod, callPrefix, ... params Uri address = new Uri(_requestUri + callPrefix + "/" + callName); HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest; wreq.Proxy = GlobalProxySelection.GetEmptyWebProxy(); wreq.Method = "POST"; wreq.ContentType = "application/x-www-form-urlencoded"; StringBuilder d = new StringBuilder(); d.Append("apikey=").Append(_apiKey).Append(parameters.getParameterString()); parameters.resetBaseParams(); byte[] bd = UTF8Encoding.UTF8.GetBytes(d.ToString()); wreq.ContentLength = bd.Length; using (Stream ps = wreq.GetRequestStream()) { ps.Write(bd, 0, bd.Length); } return(DoRequest(wreq, parameters.getOutputMode())); }
/// <summary> /// Computes a <see cref="IWebProxy">web proxy</see> resolver instance /// based on the combination of proxy-related settings in this vault /// configuration. /// </summary> /// <returns></returns> public IWebProxy GetWebProxy() { IWebProxy wp = null; if (UseNoProxy) { wp = GlobalProxySelection.GetEmptyWebProxy(); } else if (!string.IsNullOrEmpty(ProxyUri)) { var newwp = new WebProxy(ProxyUri); if (UseDefCred) { newwp.UseDefaultCredentials = true; } else if (!string.IsNullOrEmpty(Username)) { var pw = PasswordEncoded; if (!string.IsNullOrEmpty(pw)) { pw = Encoding.Unicode.GetString(Convert.FromBase64String(pw)); } newwp.Credentials = new NetworkCredential(Username, pw); } } return(wp); }
//Speed, filtering additional pages static void Main(string[] args) { const string URL = "http://www.ypsyork.org/events/?pno="; var client = new WebClient(); client.Proxy = GlobalProxySelection.GetEmptyWebProxy(); List <Common> allEvents = new List <Common>(); var pageNumber = 1; while (true) { if (!ReadPage(client, URL, allEvents, pageNumber)) { break; } pageNumber++; } var serializer = new Serializer(); var yaml = serializer.Serialize(allEvents); // Push the file to git var gitHubClient = new GitHub(); gitHubClient.WriteFileToGitHub("_data/YPS.yml", yaml); }
private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; button2.Enabled = false; string path = Path.Combine(Application.StartupPath, "temp.zip"); if (File.Exists(path)) { extractHere(); } else { WebClient webClient = new WebClient(); webClient.Proxy = GlobalProxySelection.GetEmptyWebProxy(); webClient.DownloadProgressChanged += (s, ez) => { progressBar1.Value = ez.ProgressPercentage; }; webClient.DownloadFileCompleted += (s, ez) => { progressBar1.Visible = false; extractHere(); }; webClient.DownloadFileAsync(new Uri("https://github.com/KingLycosa/acnhpoker/releases/download/0.0001/img.zip"), "temp.zip"); } }
private string GET(string callName, string callPrefix, AlchemyAPI_BaseParams parameters) { // callMethod, callPrefix, ... params StringBuilder uri = new StringBuilder(); uri.Append(_requestUri).Append(callPrefix).Append("/").Append(callName); uri.Append("?apikey=").Append(_apiKey).Append(parameters.getParameterString()); parameters.resetBaseParams(); Uri address = new Uri(uri.ToString()); HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest; wreq.Proxy = GlobalProxySelection.GetEmptyWebProxy(); byte[] postData = parameters.GetPostData(); if (postData == null) { wreq.Method = "GET"; } else { wreq.Method = "POST"; using (var ps = wreq.GetRequestStream()) { ps.Write(postData, 0, postData.Length); } } return(DoRequest(wreq, parameters.getOutputMode())); }
private void ConfigureProxy(GenericProtocol protocol) { ServicePointManager.Expect100Continue = ClientConfig.Expect100Continue; if (!((protocol) is IProxyCompatible)) { return; } var proxyProtocol = ((IProxyCompatible)protocol); IWebProxy proxy; if (ClientConfig.ProxyEnabled) { // Configuration #pragma warning disable 618 proxy = ClientConfig.ProxyAutoConfiguration ? GlobalProxySelection.Select : new WebProxy(ClientConfig.ProxyAddress, ClientConfig.ProxyPort); #pragma warning restore 618 if (proxy != null) { // Authentification if (ClientConfig.ProxyAutoAuthentication) { proxy.Credentials = CredentialCache.DefaultCredentials; } else { var netCreds = new NetworkCredential { UserName = ClientConfig.ProxyUserName, Password = ClientConfig.ProxyPassword, Domain = ClientConfig.ProxyDomain }; proxy.Credentials = netCreds; } } } else { #pragma warning disable 618 proxy = GlobalProxySelection.GetEmptyWebProxy(); #pragma warning restore 618 } var webProxy = proxy as WebProxy; if (webProxy != null && webProxy.Address == null) { #pragma warning disable 618 proxy = GlobalProxySelection.GetEmptyWebProxy(); #pragma warning restore 618 } proxyProtocol.Proxy = proxy; Log(webProxy != null ? string.Format(Strings.USING_PROXY, ((WebProxy)proxy).Address, proxy) : Strings.NOT_USING_PROXY, ESeverity.INFO); }
public static FavIconDescriptor RequestIcon(string baseUri, IWebProxy proxy, ICredentials credentials) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (proxy == null) { proxy = GlobalProxySelection.GetEmptyWebProxy(); } FavIconDescriptor ico = null; try { using (Stream stream = AsyncWebRequest.GetSyncResponseStream(baseUri, credentials, "RssBandit", proxy)) { string htmlContent = string.Empty; using (StreamReader reader = new StreamReader(stream)) { htmlContent = reader.ReadToEnd(); ico = RequestIcon(baseUri, htmlContent, proxy, credentials); } } } catch { // no default HTML page to examine for a FavIcon entry. // we do not stop here: try to get a direct download by requesting favicon.ico directly } string realIconUrl = null; if (ico == null || ico == FavIconDescriptor.Empty) { try { Uri b = new Uri(new Uri(baseUri), "favicon.ico"); realIconUrl = b.ToString(); } catch (UriFormatException) {} } if (realIconUrl == null) { return(FavIconDescriptor.Empty); } // now get the icon stream using (Stream stream = AsyncWebRequest.GetSyncResponseStream(realIconUrl, credentials, "RssBandit", proxy)) { Image img = CheckAndScaleImageFromStream(stream); if (img != null) { return(new FavIconDescriptor(realIconUrl, baseUri, DateTime.Now, img)); } } return(FavIconDescriptor.Empty); }
public static bool ReceiveARCPacket(string source, string destination, out string packet) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://arsslenserv.eb2a.com/ReceiveARCPacket.php"); request.Method = "POST"; request.Accept = "gzip, deflate"; request.Timeout = 15000; request.KeepAlive = true; request.CookieContainer = _cookieContainer; request.UserAgent = "Arsslensoft/UserAgent"; request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; string postData = "S=" + source + "&D=" + destination + "&U=ATKOCAPCRTPBR"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; request.Proxy = GlobalProxySelection.GetEmptyWebProxy(); // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. WebResponse response = request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); if (responseFromServer != "ACCESS DENIED" && responseFromServer != "" && !responseFromServer.Contains("<html>") && !responseFromServer.Contains("onfigure router")) { reader.Close(); dataStream.Close(); response.Close(); packet = Security.HexAsciiConvert(responseFromServer); return(true); } reader.Close(); dataStream.Close(); response.Close(); packet = null; return(false); } catch { packet = null; return(false); } }
public static Boolean FTPUploadFile() { try { sDirName = sDirName.Replace("\\", "/"); string sURI = "FTP://" + sFTPServerIP + "/" + sDirName + "/" + sToFileName; System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(sURI); //建立FTP連線 //設定連線模式及相關參數 myFTP.Credentials = new System.Net.NetworkCredential(sUserName, sPassWord); //帳密驗證 myFTP.KeepAlive = false; //關閉/保持 連線 myFTP.Timeout = 2000; //等待時間 myFTP.UseBinary = true; //傳輸資料型別 二進位/文字 myFTP.UsePassive = false; //通訊埠接聽並等待連接 myFTP.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //下傳檔案 /* proxy setting (不使用proxy) */ myFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy(); myFTP.Proxy = null; //上傳檔案 System.IO.FileStream myReadStream = new System.IO.FileStream(sFromFileName, FileMode.Open, FileAccess.Read); //檔案設為讀取模式 System.IO.Stream myWriteStream = myFTP.GetRequestStream(); //資料串流設為上傳至FTP byte[] bBuffer = new byte[2047]; int iRead = 0; //傳輸位元初始化 do { iRead = myReadStream.Read(bBuffer, 0, bBuffer.Length); //讀取上傳檔案 myWriteStream.Write(bBuffer, 0, iRead); //傳送資料串流 //Console.WriteLine("Buffer: {0} Byte", iRead); } while (!(iRead == 0)); myReadStream.Flush(); myReadStream.Close(); myReadStream.Dispose(); myWriteStream.Flush(); myWriteStream.Close(); myWriteStream.Dispose(); return(true); } catch (Exception ex) { Console.WriteLine("FTP Upload Fail" + "\n" + "{0}", ex.Message); //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false); iFTPReTry--; if (iFTPReTry >= 0) { return(FTPUploadFile()); } else { return(false); } } }
public void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能 { FileInfo fileInf = new FileInfo(filename); string uri = "ftp://" + ftpServerIP + fileInf.Name; Connect(uri);//连接 // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 上传文件时通知服务器文件的大小 reqFTP.ContentLength = fileInf.Length; // 缓冲大小设置为kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流(System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); try { //使用 HTTP Proxy 時,不支援要求的 FTP 命令。 //要解决以上问题,只需要在代码中指定 reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy(); //或 //reqFTP.Proxy = null; // 把上传的文件写入流 Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的kb contentLen = fs.Read(buff, 0, buffLength); // 流内容没有结束 while (contentLen != 0) { // 把内容从file stream 写入upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 关闭两个流 strm.Close(); fs.Close(); } catch (Exception ex) { //MessageBox.Show(ex.Message, "Upload Error"); throw ex; } }
/// <summary> /// 获取当前目录下文件列表(仅文件) /// </summary> /// <returns></returns> public string[] GetFileList(string mask) { string[] downloadFiles = null; StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; ////reqFTP.Proxy = WebRequest.DefaultWebProxy; reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy(); WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine(); if (string.IsNullOrEmpty(line)) { return(downloadFiles); } while (line != null) { if (mask.Trim() != string.Empty && mask.Trim() != "*.*") { string mask_ = mask.Substring(0, mask.IndexOf("*")); if (line.Substring(0, mask_.Length) == mask_) { result.Append(line); result.Append("\n"); } } else { result.Append(line); result.Append("\n"); } line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return(result.ToString().Split('\n')); } catch (Exception ex) { throw new Exception(ex.Message); } }
protected RemoteFunction(string json, int port, string field) { this.Json = json; this.Port = port; this.Field = field; this.ScriptConfig = new ProcessStartInfo(); this.ScriptConfig.FileName = "run_core"; this.ScriptConfig.Arguments = $"--core {this.Json} --port {this.Port}"; this.ScriptConfig.WindowStyle = ProcessWindowStyle.Hidden; this.Client.Proxy = GlobalProxySelection.GetEmptyWebProxy(); this.Client.BaseAddress = $"http://localhost:{this.Port}"; this.Client.Headers = null; }
private void setCurrentWeather() { curThreadDone = false; try { Object[] data = new Object[3]; XmlDocument xdoc = new XmlDocument(); xdoc.Load("http://api.wxbug.net/getLiveWeatherRSS.aspx?ACode=A5678056775&cityCode=" + CITYCODE + "&unittype=1&outputtype=1"); progressBar1.Invoke(new progressUpdateCallback(progressUpdate), new Object[] { progressBar1, 10 }); if (xdoc.InnerText.Length > 0) { XmlNodeList temp = xdoc.GetElementsByTagName("aws:temp"); XmlNodeList current = xdoc.GetElementsByTagName("aws:current-condition"); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(current[0].Attributes[0].Value); req.ReadWriteTimeout = 10000; //10 seconds req.Timeout = 15000; //15 seconds req.KeepAlive = false; req.Proxy = GlobalProxySelection.GetEmptyWebProxy(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream pstream = resp.GetResponseStream(); data[0] = temp[0].InnerText + "°C"; data[1] = current[0].InnerText; data[2] = new Bitmap(pstream); pstream.Close(); resp.Close(); progressBar1.Invoke(new progressUpdateCallback(progressUpdate), new Object[] { progressBar1, 10 }); label8.Invoke(new labelUpdateCallback(labelUpdate), new Object[] { label8, data[0] }); label7.Invoke(new labelUpdateCallback(labelUpdate), new Object[] { label7, data[1] }); pictureBox1.Invoke(new pictureBoxUpdateCallback(pictureBoxUpdate), new Object[] { pictureBox1, data[2] }); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("setCurrentWeather Exception: " + e.Message); } curThreadDone = true; }
private void PrepareView() { using (WebClient webClient = new WebClient()) { webClient.Proxy = GlobalProxySelection.GetEmptyWebProxy(); webClient.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; try { htmlContent = webClient.DownloadString(uri); } catch (Exception) { throw; } } }
private WebClient CreateWebClient() { var webClient = new Http10WebClient { Proxy = GlobalProxySelection.GetEmptyWebProxy(), }; if (_isGuestMode == false) { webClient.Credentials = new NetworkCredential(_userName, _password); } webClient.Headers.Add("Accept", "application/json"); return(webClient); }
public PHPRPC_Client() { formatter = new PHPFormatter(encoding, assemblies); clientID = "dotNET" + new Random().Next().ToString() + DateTime.Now.Ticks.ToString() + (sid++).ToString(); #if !SILVERLIGHT try { #if (PocketPC || Smartphone || WindowsCE || NET1) proxy = GlobalProxySelection.GetEmptyWebProxy(); #else proxy = HttpWebRequest.DefaultWebProxy; #endif } catch { proxy = null; } #endif }
public void GetEmptyWebProxy_Success() { var empty1 = GlobalProxySelection.GetEmptyWebProxy(); Assert.True(empty1.IsBypassed(null)); Assert.Null(empty1.GetProxy(null)); Uri someUri = new Uri("http://foo.com/bar"); Assert.True(empty1.IsBypassed(someUri)); Assert.Equal(someUri, empty1.GetProxy(someUri)); Assert.Null(empty1.Credentials); var empty2 = GlobalProxySelection.GetEmptyWebProxy(); Assert.NotEqual(empty1, empty2); // new instance each time }
//列出目录 private string[] ListDirectory(string uristring) { try { Uri uri = new Uri(ftphost + uristring); FtpWebRequest listRequest = ( FtpWebRequest )WebRequest.Create(uri); listRequest.Credentials = new NetworkCredential(username, password); listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; listRequest.Proxy = GlobalProxySelection.GetEmptyWebProxy(); FtpWebResponse listResponse = ( FtpWebResponse )listRequest.GetResponse(); Stream responseStream = listResponse.GetResponseStream( ); StreamReader readStream = new StreamReader(responseStream, System.Text.Encoding.Default); if (readStream != null) { DirectoryListParser parser = new DirectoryListParser(readStream.ReadToEnd()); FileStruct[] fs = parser.FullListing; List <string> returns = new List <string>(); foreach (FileStruct element in fs) { if (element.IsDirectory) { returns.Add(element.Name); } } listResponse.Close(); responseStream.Close(); readStream.Close(); if (returns.Count > 0) { return(returns.ToArray()); } else { return(null); } } listResponse.Close(); responseStream.Close(); readStream.Close(); return(null); } catch (Exception e) { MessageBox.Show(e.ToString(), "FTP访问错误"); return(new string[] { "" }); } }
public void GetEmptyWebProxy_Success() { #pragma warning disable 0618 //GlobalProxySelection is Deprecated. var empty1 = GlobalProxySelection.GetEmptyWebProxy(); #pragma warning restore 0618 Assert.True(empty1.IsBypassed(null)); Assert.Null(empty1.GetProxy(null)); Uri someUri = new Uri("http://foo.com/bar"); Assert.True(empty1.IsBypassed(someUri)); Assert.Equal(someUri, empty1.GetProxy(someUri)); Assert.Null(empty1.Credentials); #pragma warning disable 0618 //GlobalProxySelection is Deprecated. var empty2 = GlobalProxySelection.GetEmptyWebProxy(); #pragma warning restore 0618 Assert.NotEqual(empty1, empty2); // new instance each time }
private String getHttp(String url) { String results = ""; if (url.Length > 0) { try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:6.0.1) Gecko/20100101 Firefox/6.0.1"; req.ReadWriteTimeout = 5000; //2 seconds req.Timeout = 5000; //2 seconds req.KeepAlive = false; req.Proxy = GlobalProxySelection.GetEmptyWebProxy(); req.Method = "GET"; req.AllowAutoRedirect = true; if (sessCookie.Length > 0) { req.Headers.Add("Cookie", sessCookie); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); if (resp.Headers["Set-Cookie"] != null) { sessCookie = resp.Headers["Set-Cookie"]; } StreamReader streamReader = new StreamReader(resp.GetResponseStream()); results = streamReader.ReadToEnd(); streamReader.Close(); resp.Close(); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("getHttp Exception: " + e.Message); } } return(results); }
public static void Main() { // Create a request for the Web page at www.contoso.com. WebRequest request = WebRequest.Create("http://www.contoso.com"); // This application doesn't want the proxy to be used so it sets // the global proxy to an empty proxy. IWebProxy myProxy = GlobalProxySelection.GetEmptyWebProxy(); GlobalProxySelection.Select = myProxy; // Get the response. WebResponse response = request.GetResponse(); // Display the response to the console. Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); Console.WriteLine(reader.ReadToEnd()); // Clean up. reader.Close(); stream.Close(); response.Close(); }
/// <summary> /// Initializes the WebProxy object. /// </summary> /// <param name="proxy">The proxy server address.</param> /// <param name="proxyUser">The user name for proxy authentication.</param> /// <param name="proxyPassword">The password for proxy authentication.</param> private void InitializeWebProxy(Uri proxy, string proxyUser, string proxyPassword) { if (proxy != null) { if ((proxyUser == null) || (proxyUser == String.Empty)) { webProxy = new WebProxy(proxy, false); } else { webProxy = new WebProxy( proxy, false, new string[] {}, new NetworkCredential(proxyUser, proxyPassword, proxy.ToString())); } } else { webProxy = GlobalProxySelection.GetEmptyWebProxy(); } }
/// <summary> /// 下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> public void Download(string filePath, string fileName) { FtpWebRequest reqFTP; try { FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); //reqFTP.Proxy = WebRequest.DefaultWebProxy; reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy(); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { WriteTraceLog.Error("FtpWeb: Upload Error --> " + ex.Message); throw new Exception(string.Format("FTP Upload Error -->{0}", ex.Message)); } }
//复制文件 private bool CopyFile(string uristring, string target) { try { Uri uri = new Uri(uristring); FtpWebRequest listRequest = ( FtpWebRequest )WebRequest.Create(uri); listRequest.Credentials = new NetworkCredential(username, password); listRequest.Method = WebRequestMethods.Ftp.Rename; listRequest.Proxy = GlobalProxySelection.GetEmptyWebProxy(); FtpWebResponse listResponse = ( FtpWebResponse )listRequest.GetResponse(); if (listResponse.StatusCode == FtpStatusCode.PathnameCreated) { listResponse.Close(); return(true); } else { listResponse.Close(); return(false); } } catch (Exception) { return(false); } }
//删除目录 private bool DeleteDirectory(string uristring) { try { Uri uri = new Uri(uristring); FtpWebRequest listRequest = ( FtpWebRequest )WebRequest.Create(uri); listRequest.Credentials = new NetworkCredential(username, password); listRequest.Method = WebRequestMethods.Ftp.RemoveDirectory; listRequest.Proxy = GlobalProxySelection.GetEmptyWebProxy(); FtpWebResponse listResponse = ( FtpWebResponse )listRequest.GetResponse(); if (listResponse.StatusCode == FtpStatusCode.FileActionOK) { listResponse.Close(); return(true); } else { listResponse.Close(); return(false); } } catch (Exception) { return(false); } }