2012-01-10 2 views
5

독일의 특정 회사에 문제가 있습니다. 그들은 네트워크에서 프록시를 사용하고 프로그램은 서버와 통신 할 수 없습니다.C# Internet Explorer에서 프록시 설정 가져 오기

IE는이 설정을 사용하여 작동합니다

Their settings

그것은 의미

: 같은

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; 
    } 

} 

내 프로그램 로그를 : 자동으로이 코드입니다 설정

을 감지

[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. 

사용자를 작성하고 proxy.ini 파일로 전달하면 프로그램이 작동합니다. 그러나 문제는 그들이 그렇게 할 수 없다는 것입니다. 그리고 어쨌든 IE는 그것없이 작동합니다. IE 또는 시스템에서 해당 설정을 가져올 수있는 방법이 있습니까?

+0

우선 catch (Exception e)에서 e.message를 제거하고 e를 로그합니다. 이렇게하면 스택 추적을 얻을 수 있고 어떤 객체가 null인지 파악할 수 있습니다. – mattypiper

+0

ttymatty : 여전히 완전한 코드는 아니지만 문제는 '객체 참조가 객체 인스턴스로 설정되지 않았습니다.'입니다.'Response = (HttpWebResponse) 요청을 시도 할 때'원격 서버가 오류를 반환했습니다 : (407)'을 봅니다. GetResponse();'. 승인되지 않았기 때문에 응답이 null입니다. – Kaminari

답변

13

GetSystemWebProxy을 사용하면 시스템 기본 프록시를 반환 할 수 있습니다.

WebRequest.DefaultProxy = WebRequest.GetSystemWebProxy(); 

그러나 모든 HttpWebRequest이 자동으로 기본적으로이 정보를 작성해야합니다. 예를 들어, 독립 실행 형 콘솔 응용 프로그램의 다음 스 니펫은 PAC 파일이 구성된 시스템에 올바른 정보를 인쇄해야합니다.

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

같은 것이 아니라 :'request.Proxy = WebRequest.DefaultWebProxy;'? – Kaminari

+0

네가 맞습니다. 게시 한 코드를 실행하면 시스템에 프록시가 있는지 여부가 결정됩니다. 인터넷 옵션에서 선택한 "자동 구성"으로 말하기는 어렵습니다. – mattypiper

+0

작동하지 않습니다. 그 밖의 문제는 어디에있을 수 있습니까? 요청 헤더에? – Kaminari

7

시스템 프록시 자격 증명을 반환하려면 DefaultNetworkCredentials을 사용하십시오.

request.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; 
관련 문제