2012-01-10 37 views
5

tôi gặp sự cố ở một số công ty ở Đức. Họ sử dụng proxy trong mạng của họ và chương trình của tôi không thể giao tiếp với máy chủ.C# Nhận cài đặt proxy từ Internet Explorer

IE làm việc với các thiết lập này:

Their settings

Nó có nghĩa là: Tự động phát hiện các thiết lập

Đây là mã:

public static bool CompleteValidation(string regKey) 
{ 
    string uri = "***"; 

    int c = 1; 
    if (Counter < 5) c = 6 - Counter; 
    string response = ""; 
    try 
    { 
     System.Net.ServicePointManager.Expect100Continue = false; 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); 
     request.AllowWriteStreamBuffering = true; 
     request.Method = "POST"; 
     request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0"; 
     request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
     request.Headers.Add(HttpRequestHeader.AcceptLanguage, "pl,en-us;q=0.7,en;q=0.3"); 
     request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate"); 
     request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-2,utf-8;q=0.7,*;q=0.7"); 
     request.KeepAlive = true; 

     //proxy settings 
     string exepath = Path.GetDirectoryName(Application.ExecutablePath); 
     string proxySettings = exepath + @"\proxy.ini"; 
     WebProxy wp = new WebProxy(); 
     if (File.Exists(proxySettings)) { 
      request.Proxy = WebRequest.DefaultWebProxy; 
      IniFile ini = new IniFile(proxySettings); 
      string user = ini.IniReadValue("Proxy", "User"); 
      string pass = ini.IniReadValue("Proxy", "Password"); 
      string domain = ini.IniReadValue("Proxy", "Domain"); 
      string ip = ini.IniReadValue("Proxy", "IP"); 
      string port_s = ini.IniReadValue("Proxy", "Port"); 
      int port = 0; 
      if (!string.IsNullOrEmpty(ip)) 
      { 
       if (!string.IsNullOrEmpty(port_s)) 
       { 
        try 
        { 
         port = Convert.ToInt32(port_s); 
        } 
        catch (Exception e) 
        { 
         ErrorLog.AddToLog("Problem with conversion of port:"); 
         ErrorLog.AddToLog(e.Message); 
         ErrorLog.ShowLogWindow(); 
        } 
        wp = new WebProxy(ip, port); 
       } else { 
        wp = new WebProxy(ip); 
       } 

      } 
      if (string.IsNullOrEmpty(domain)) 
       wp.Credentials = new NetworkCredential(user, pass); 
      else 
       wp.Credentials = new NetworkCredential(user, pass, domain); 
      request.Proxy = wp; 
     } 

     string post = "***"; 
     request.ContentLength = post.Length; 
     request.ContentType = "application/x-www-form-urlencoded"; 
     StreamWriter writer = null; 
     try 
     { 
      writer = new StreamWriter(request.GetRequestStream()); // Here is the WebException thrown 
      writer.Write(post); 
      writer.Close(); 
     } 
     catch (Exception e) 
     { 
      ErrorLog.AddToLog("Problem with request sending:"); 
      ErrorLog.AddToLog(e.Message); 
      ErrorLog.ShowLogWindow(); 
     } 
     HttpWebResponse Response = null; 
     try 
     { 
      Response = (HttpWebResponse)request.GetResponse(); 
     } 
     catch (Exception e) 
     { 
      ErrorLog.AddToLog("Problem with response:"); 
      ErrorLog.AddToLog(e.Message); 
      ErrorLog.ShowLogWindow(); 
     } 

     //Request.Proxy = WebProxy.GetDefaultProxy(); 
     //Request.Proxy.Credentials = CredentialCache.DefaultCredentials; 
     string sResponseHeader = Response.ContentEncoding; // get response header 

     if (!string.IsNullOrEmpty(sResponseHeader)) 
     { 
      if (sResponseHeader.ToLower().Contains("gzip")) 
      { 
       byte[] b = DecompressGzip(Response.GetResponseStream()); 
       response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b); 
      } 
      else if (sResponseHeader.ToLower().Contains("deflate")) 
      { 
       byte[] b = DecompressDeflate(Response.GetResponseStream()); 
       response = System.Text.Encoding.GetEncoding(Response.ContentEncoding).GetString(b); 
      } 
     } 
     // uncompressed, standard response 
     else 
     { 
      StreamReader ResponseReader = new StreamReader(Response.GetResponseStream()); 
      response = ResponseReader.ReadToEnd(); 
      ResponseReader.Close(); 
     } 
    } 
    catch (Exception e) 
    { 
     ErrorLog.AddToLog("Problem with comunication:"); 
     ErrorLog.AddToLog(e.Message); 
     ErrorLog.ShowLogWindow(); 
    } 

    if (response == "***") 
    { 
     SaveKeyFiles(); 
     WriteRegKey(regKey); 
     RenewCounter(); 
     return true; 
    } 
    else 
    { 
     return false; 
    } 

} 

chương trình của tôi ghi nó như:

[09:13:18] Searching for hardware ID 
[09:13:56] Problem with response: 
[09:13:56] The remote server returned an error: (407) Proxy Authentication Required. 
[09:15:04] problem with comunication: 
[09:15:04] Object reference not set to an object instance. 

Nếu họ viết người dùng và chuyển vào tệp proxy.ini, chương trình sẽ hoạt động. Nhưng vấn đề là họ không thể làm điều đó. Và bằng cách nào đó IE hoạt động mà không có nó. Có cách nào để có được những thiết lập từ IE hoặc hệ thống?

+0

Trước hết, trong quá trình bắt (Ngoại lệ e) loại bỏ e.message và chỉ cần ghi nhật ký điện tử. Bằng cách này, bạn nhận được một dấu vết ngăn xếp và bạn có thể tìm ra đối tượng nào là null. – mattypiper

+0

ttymatty: mã vẫn chưa hoàn chỉnh nhưng vấn đề sớm hơn 'Tham chiếu đối tượng không được đặt thành thể hiện đối tượng.' Nhìn vào' Máy chủ từ xa trả về lỗi: (407) 'khi cố gắng yêu cầu' Response = (HttpWebResponse). GetResponse(); '. Phản hồi là null vì nó không được ủy quyền. – Kaminari

Trả lời

13

Sử dụng GetSystemWebProxy để trả lại proxy mặc định của hệ thống là gì.

WebRequest.DefaultProxy = WebRequest.GetSystemWebProxy(); 

Nhưng mỗi HttpWebRequest sẽ tự động được điền thông tin này theo mặc định. Ví dụ: đoạn mã sau trong ứng dụng bảng điều khiển độc lập sẽ in thông tin chính xác trên hệ thống có tệp PAC được định cấu hình.

HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com"); 

    // Obtain the 'Proxy' of the Default browser. 
    IWebProxy proxy = myWebRequest.Proxy; 
    // Print the Proxy Url to the console. 
    if (proxy != null) 
    { 
     Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri)); 
    } 
    else 
    { 
     Console.WriteLine("Proxy is null; no proxy will be used"); 
    } 
+0

Không phải là nó giống như: 'request.Proxy = WebRequest.DefaultWebProxy;'? – Kaminari

+0

Có bạn đúng. Nếu bạn thực thi mã tôi đăng, hệ thống có proxy hay không? Thật khó để nói với "cấu hình tự động" được chọn trong Tùy chọn Internet. – mattypiper

+0

Nó không hoạt động. Trường hợp khác có thể là một vấn đề? Trong tiêu đề yêu cầu? – Kaminari

7

Sử dụng DefaultNetworkCredentials để trả lại thông tin xác thực proxy hệ thống.

request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 
Các vấn đề liên quan