使用自动组态指令码情况下取得相应的代理地址

参考网址:http://support.microsoft.com/kb/873199 

 

在 Managed 程式碼中使用 autoproxy

如果要在 Managed 程式碼中實作 autoproxy,請依照下列步驟執行:

  1. 建立使用 autoproxy 的 Managed 的 DLL。
  2. 建立範例應用程式,以確認 autoproxy 實作。
建立使用 autoproxy 的 Managed 的 DLL

若要建立受管理的 DLL,使用 WinHTTP autoproxy 函式來擷取 Proxy 資訊,請依照下列步驟執行:

  1. 啟動 Microsoft Visual Studio.NET。
  2. 在 [檔案] 功能表上指向 [新增],然後按一下 [專案]。出現 [新增專案] 對話方塊。
  3. 按一下 [專案類型 下的 [Visual C++ 專案,然後按一下 [範本] 下方的 [受管理的 C + + 類別庫

    如果您使用的 Visual Studio.NET 2003年,按一下 [範本] 下方的 [類別程式庫 (.NET)]。
  4. 在 [名稱] 方塊中輸入 Autoproxy,],然後再按一下 [確定]]。
  5. 在 [方案總管] 中 Autoproxy.h,] 上按一下滑鼠右鍵,然後按一下 [開啟舊檔]。
  6. Autoproxy.h 檔案中現有的程式碼取代下列程式碼:

 

// AutoProxy.h
#define UNICODE
#include <windows.h>
#include <wchar.h>
#include <winhttp.h>
#include <stdio.h>
#pragma comment (lib, "winhttp.lib")

#pragma once

using namespace System;
using namespace System::Runtime::InteropServices;

namespace AutoProxy
{
   public __gc class Class1
   {
      private:
          TCHAR* szUrl;
          TCHAR* szAutoProxyLocation;
      public:
          Class1 (String* szUrlParam)
          {
              TCHAR szMessage[1024];
              szUrl = (TCHAR *)(void*)Marshal::StringToCoTaskMemUni(szUrlParam);
              swprintf (szMessage, L"Initializing class for URL %s with autorpxy\n",
        szUrl);
              OutputDebugString (szMessage);
              szAutoProxyLocation = NULL;
              CoInitialize(NULL);
          };
          Class1 (String* szUrlParam, String* proxyUrl)
          {
              TCHAR szMessage[1024];
              szUrl = (TCHAR *)(void*)Marshal::StringToCoTaskMemUni(szUrlParam);
              szAutoProxyLocation = (TCHAR*)(void*)Marshal::StringToCoTaskMemUni(proxyUrl);
              swprintf (szMessage, L"Initilizing class for url %s with proxy location %s\n",
        szUrl, szAutoProxyLocation);
              OutputDebugString (szMessage);
              CoInitialize(NULL);
          };

          ~Class1 ()
          {
              OutputDebugString (L"Class1 destruct\n");
              CoUninitialize ();
          };

          String* GetProxyForUrl()//throw (TCHAR*)
          {
              TCHAR szError [1024];
              HINTERNET hHttpSession = NULL;
              WINHTTP_AUTOPROXY_OPTIONS AutoProxyOptions;
              WINHTTP_PROXY_INFO ProxyInfo;
              DWORD cbProxyInfoSize = sizeof(ProxyInfo);
              TCHAR* szProxy;
              ZeroMemory( &AutoProxyOptions, sizeof(AutoProxyOptions) );
              ZeroMemory( &ProxyInfo, sizeof(ProxyInfo) );
              hHttpSession = WinHttpOpen( L"WinHTTP AutoProxy Sample/1.0",
                                          WINHTTP_ACCESS_TYPE_NO_PROXY,
                                          WINHTTP_NO_PROXY_NAME,
                                          WINHTTP_NO_PROXY_BYPASS,0
                                        );
              // Exit if the WinHttpOpen function fails.
             if( !hHttpSession )
             {
                  // Clean the WINHTTP_PROXY_INFO structure.
                  if( ProxyInfo.lpszProxy != NULL )
                       GlobalFree(ProxyInfo.lpszProxy);
                  if( ProxyInfo.lpszProxyBypass != NULL )
                       GlobalFree( ProxyInfo.lpszProxyBypass );
             }
             // Set up the autoproxy call.
             if (szAutoProxyLocation)
             {
                 // The proxy auto-configuration URL is already known. 
                 // Therefore, auto-detection is not required.
                AutoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
   
                // Set the proxy auto configuration URL.
                AutoProxyOptions. lpszAutoConfigUrl = szAutoProxyLocation;
             }
             else
             {
                 // Use auto-detection because you do not know a PAC URL.
                 AutoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
                 // Use both Dynamic Host Configuration Protocol (DHCP)
                 // and Domain Name System (DNS) based auto-detection.
                 AutoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP

                 |WINHTTP_AUTO_DETECT_TYPE_DNS_A;
             }
            // If obtaining the PAC script requires NTLM/Negotiate
            // authentication, automatically supply the domain credentials
            // of the client.
            AutoProxyOptions.fAutoLogonIfChallenged = TRUE;
            // Call the WinHttpGetProxyForUrl function with our target URL.
            if( WinHttpGetProxyForUrl( hHttpSession,szUrl,&AutoProxyOptions,&ProxyInfo))  

            {
                 switch (ProxyInfo.dwAccessType)
                 {
                      case WINHTTP_ACCESS_TYPE_DEFAULT_PROXY:
                         OutputDebugString (L"WINHTTP_ACCESS_TYPE_DEFAULT_PROXY\n");
                         break;
                      case WINHTTP_ACCESS_TYPE_NO_PROXY:
                         OutputDebugString (L"WINHTTP_ACCESS_TYPE_NO_PROXY\n");
                         break;
                      case WINHTTP_ACCESS_TYPE_NAMED_PROXY:
                         OutputDebugString (L"WINHTTP_ACCESS_TYPE_NAMED_PROXY\n");
                         break;
                 }
                 if (ProxyInfo.lpszProxy)
                 {
                     szProxy = new TCHAR [lstrlen (ProxyInfo.lpszProxy)];
                     lstrcpy (szProxy, ProxyInfo.lpszProxy);
                 }
                 // Clean the WINHTTP_PROXY_INFO structure.
                 if (ProxyInfo.lpszProxy != NULL)
                     GlobalFree(ProxyInfo.lpszProxy);
                 if (ProxyInfo.lpszProxyBypass != NULL)                                     

                     GlobalFree(ProxyInfo.lpszProxyBypass);
             }
             else
             {
                 DWORD dwErr = GetLastError();
                 switch (dwErr)
                 {
                     case ERROR_WINHTTP_AUTODETECTION_FAILED:
                         swprintf(szError, L"ERROR_WINHTTP_AUTODETECTION_FAILED\n");
                         break;
                     case ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT:
                         swprintf(szError,L"ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT\n");
                         break;
                     case ERROR_WINHTTP_INCORRECT_HANDLE_TYPE:
                         swprintf(szError,L"ERROR_WINHTTP_INCORRECT_HANDLE_TYPE\n");
                         break;
                     case ERROR_WINHTTP_INVALID_URL:
                         swprintf(szError,L"ERROR_WINHTTP_INVALID_URL\n");
                         break;
                     case ERROR_WINHTTP_LOGIN_FAILURE:
                         swprintf(szError,L"ERROR_WINHTTP_LOGIN_FAILURE\n");
                         break;
                     case ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT:
                         swprintf(szError,L"ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT\n");
                         break;
                     case ERROR_WINHTTP_UNRECOGNIZED_SCHEME:
                         swprintf(szError,L"ERROR_WINHTTP_UNRECOGNIZED_SCHEME\n");
                         break;
                     default:
                         swprintf (szError, L"Error %d\n", dwErr);
                }
                throw (new Exception(szError));

             }
            // Close the WinHTTP handles.
            if( hHttpSession != NULL )
                  WinHttpCloseHandle( hHttpSession ); 
            // Return the proxy settings.
            Marshal::FreeHGlobal(szUrl);
            return new String (szProxy);

        }
   };
}

 

 

 

  1. 在 [方案總管] 中 Autoproxy,] 上按一下滑鼠右鍵,然後按一下 [內容]。Autoproxy 屬性頁] 對話方塊隨即出現。
  2. 在左窗格中按一下 [連結器],請在 [組態屬性,] 下,然後按一下 [輸入]。
  3. 在右窗格中的 [其他相依性] 方塊中,鍵入 path of winhttp library \winhttp.lib"

    附註path of winhttp library 是 Winhttp.lib 檔案在您的電腦上的預留位置。
  4. 在 [其他相依性] 方塊中,輸入 msvcrt.lib
  5. 在 [強制符號參考] 方塊鍵入 __DllMainCRTStartup@12,],然後再按一下 [確定]]。
  6. 在 建置] 功能表上按一下 [建置方案] 建置專案]。

注意:運到__gc 編譯出錯問題,需要在Autoproxy屬性頁-->組態屬性-->c/c++-->命令列,其他選項處加  /clr:oldSyntax  命令

建立範例應用程式,以確認 autoproxy 實作

 AutoProxy.Class1 myProxy = new AutoProxy.Class1("https://docss.cntouch.com", "http://ip/PAC/proxy.pac");
            try
            {
                string Text = myProxy.GetProxyForUrl();

}catch(Exception e)

{

}

 

  1. 附註 在此程式碼 http://ip/PAC/proxy.pac 是 autoproxy 組態檔的 URL 路徑。如果您沒有在電腦上設定的 autoproxy 可以依照下列步驟設定 autoproxy 供測試之用:
    1. 啟動 [記事本]。
    2. 將下列程式碼貼入 「 記事本 」 中:
    3. function FindProxyForURL(url , host)
    4. {
      1. return "PROXY 192.168.1.1:8080";
    5. }
    6. 這段程式碼中的 附註192.168.1.1 是 Proxy 伺服器的 IP 位址,而 8080 是您可以透過它存取 Proxy 伺服器的連接埠。
    7. 將檔案儲存為 Proxy.pac。
    8. 建立您在步驟 6 c 建立 Proxy.pac 檔案的虛擬目錄。

      如需有關建立虛擬目錄的詳細資訊,按一下 [下列面的文件編號,檢視 「 Microsoft 知識庫 」 中的發行項]:
      172138   如何建立虛擬目錄在網際網路資訊服務 (IIS)
      附註內容資料夾路徑必須是您儲存 Proxy.pac 檔案的位置資料夾的路徑。
  2. 在 建置] 功能表上按一下 [建置方案] 建置應用程式]。
  3. 在 [偵錯] 功能表上按一下 [開始] 執行應用程式]。您可以看到 Proxy 設定在輸出中。

 

//取得本机的proxy

public string getProxy()
        {
            string sSubKey = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";

            string autoConfigUrl = getKeyValue(sSubKey, "AutoConfigURL");   //取得本机的自动组态指令码
            if (autoConfigUrl == "")    //为空则表示没有设定自动组态指令码
            {
                string sProxyEnable = getKeyValue(sSubKey, "ProxyEnable");   //取得本机是否使用代理
                if (sProxyEnable == "1")
                {
                    return getKeyValue(sSubKey, "ProxyServer");   //取得代理地址
                }
                return null;
            }
            else
            {
                AutoProxy.Class1 myProxy = new AutoProxy.Class1(http://blog.csdn.net/junjieking, autoConfigUrl);
                return myProxy.GetProxyForUrl();
            }
        }

        public string getKeyValue(string sSubKey, string sKey)   //读取注册表
        {
            string value = "";
            RegistryKey key = Registry.CurrentUser;
            RegistryKey subKey = null;
            try
            {
                subKey = key.OpenSubKey(sSubKey);
                value = subKey.GetValue(sKey).ToString();
            }
            catch (Exception e)
            {

            }
            finally
            {
                subKey.Close();
            }
            return value;
           
        }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值