2009-10-13 28 views
10

我使用FtpWebRequest做一些FTP的东西,我需要直接连接(无代理)。但WebRequest.DefaultWebProxy包含IE代理设置(我认为)。如何从WebRequest中删除代理并保持DefaultWebProxy不变

WebRequest request = WebRequest.Create("ftp://someftpserver/"); 
// request.Proxy is null here so setting it to null does not have any effect 
WebResponse response = request.GetResponse(); 
// connects using WebRequest.DefaultWebProxy 

我的代码是在一个巨大的应用程序一块,我不想改变WebRequest.DefaultWebProxy,因为它是全球性的静态属性,它可以对应用程序的其他部分产生不利影响。

任何想法如何做到这一点?

回答

19

尝试代理设置为空WebProxy,即:

request.Proxy = new WebProxy(); 

这应该创建一个空的代理。

+0

是啊,这是卓有成效的。谢谢 – Elephantik 2009-10-13 12:50:52

+0

没有probs,这一个难题前不久。 – 2009-10-13 12:53:21

+0

值得注意的是[MSDN文档](https://msdn.microsoft.com/en-us/library/czdt10d3(v = vs.110).aspx)表示使用'GlobalProxySelection.GetEmptyWebProxy()'获取一个空的代理。但是,如果你尝试这样做,Visual Studio会通知你''GlobalProxySelection'类已经过时了,你应该使用'WebRequest.DefaultWebProxy'来代替......这正是OP不需要**的东西。 – David 2017-06-14 12:22:11

7

实际上将其设置为null将是足够的,以及禁用自动代理检测,你可能会节省一些周期:)

request.Proxy = null; 

http://msdn.microsoft.com/en-us/library/fze2ytx2.aspx

+0

其实,如果我没有记错的话,设置为null没有帮助(如片段评论中所述)。禁用自动代理检测会影响我不能做的其他应用程序。不管怎么说,还是要谢谢你 – Elephantik 2010-04-06 13:02:10

0
 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(yourRequestUrl); 
     if (webRequest.Proxy != null) 
     { 
      webRequest.Proxy = null; 
     } 

     webRequest.KeepAlive = true; 
     webRequest.Method = "POST"; 
     webRequest.ContentType = "application/json"; 
     var json = JsonConvert.SerializeObject(yourObject); 
     ASCIIEncoding encoder = new ASCIIEncoding(); 
     byte[] postBytes = encoder.GetBytes(json); 
     webRequest.ContentLength = postBytes.Length; 
     webRequest.CookieContainer = new CookieContainer(); 
     String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", userName, password))); 
     webRequest.Headers.Add("Authorization", "Basic " + encoded); 
     Stream requestStream = webRequest.GetRequestStream(); 
     requestStream.Write(postBytes, 0, postBytes.Length); 
     requestStream.Close(); 

     HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse(); 
     string result; 
     using (StreamReader rdr = new StreamReader(response.GetResponseStream())) 
     { 
       result = rdr.ReadToEnd(); 
} 
相关问题