代码之家  ›  专栏  ›  技术社区  ›  Elephantik

如何从webrequest中删除代理并保持默认webproxy不变

  •  13
  • Elephantik  · 技术社区  · 16 年前

    我使用ftpWebRequest来做一些ftp的事情,我需要直接连接(没有代理)。但是webrequest.defaultwebproxy包含IE代理设置(我估计)。

    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 因为它是全局静态属性,可能会对应用程序的其他部分产生不利影响。

    知道怎么做吗?

    3 回复  |  直到 10 年前
        1
  •  23
  •   Alastair Pitts    16 年前

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

    request.Proxy = new WebProxy();
    

    这将创建一个空代理。

        2
  •  9
  •   dr. evil    16 年前

    实际上,将其设置为空将足以禁用自动代理检测,您可能会节省一些周期:)

    request.Proxy = null;
    

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

        3
  •  0
  •   Andrei    10 年前
            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();
    }