Partager via


Fonctions AutoProxy WinHTTP

WinHTTP implémente le protocole WPAD à l’aide de la fonction WinHttpGetProxyForUrl avec deux fonctions utilitaires prises en charge, WinHttpDetectAutoProxyConfigUrl et WinHttpGetIEProxyConfigForCurrentUser.

La prise en charge d’AutoProxy n’est pas entièrement intégrée à la pile HTTP dans WinHTTP. Avant d’envoyer une requête, l’application doit appeler WinHttpGetProxyForUrl pour obtenir le nom d’un serveur proxy, puis appeler WinHttpSetOption à l’aide de WINHTTP_OPTION_PROXY pour définir la configuration du proxy sur le handle de requête WinHTTP créé par WinHttpOpenRequest.

La fonction WinHttpGetProxyForUrl peut exécuter les trois étapes du protocole WPAD décrit dans la vue d’ensemble précédente : (1) découvrez l’URL PAC, (2) téléchargez le fichier de script PAC, (3) exécutez le code de script et retournez la configuration du proxy dans une structure WINHTTP_PROXY_INFO. Si l’application connaît à l’avance l’URL PAC, elle peut le spécifier pour WinHttpGetProxyForUrl.

L’exemple de code suivant utilise l’autoproxy. Il configure une requête HTTP GET en créant d’abord la connexion de session WinHTTP et les handles de requête. L’appel WinHttpOpen spécifie WINHTTP_ACCESS_TYPE_NO_PROXY pour la configuration du proxy initial, pour indiquer que les demandes sont envoyées directement au serveur cible par défaut. À l’aide de l’autoproxy, il définit ensuite la configuration du proxy directement sur le handle de requête.

  HINTERNET hHttpSession = NULL;
  HINTERNET hConnect     = NULL;
  HINTERNET hRequest     = NULL;
  
  WINHTTP_AUTOPROXY_OPTIONS  AutoProxyOptions;
  WINHTTP_PROXY_INFO         ProxyInfo;
  DWORD                      cbProxyInfoSize = sizeof(ProxyInfo);
  
  ZeroMemory( &AutoProxyOptions, sizeof(AutoProxyOptions) );
  ZeroMemory( &ProxyInfo, sizeof(ProxyInfo) );
  
//
// Create the WinHTTP session.
//
  hHttpSession = WinHttpOpen( L"WinHTTP AutoProxy Sample/1.0",
                              WINHTTP_ACCESS_TYPE_NO_PROXY,
                              WINHTTP_NO_PROXY_NAME,
                              WINHTTP_NO_PROXY_BYPASS,
                              0 );
  
// Exit if WinHttpOpen failed.
  if( !hHttpSession )
    goto Exit;
  
//
// Create the WinHTTP connect handle.
//
  hConnect = WinHttpConnect( hHttpSession,
                             L"www.microsoft.com",
                             INTERNET_DEFAULT_HTTP_PORT,
                             0 );
  
// Exit if WinHttpConnect failed.
  if( !hConnect )
    goto Exit;
  
//
// Create the HTTP request handle.
//
  hRequest = WinHttpOpenRequest( hConnect,
                                 L"GET",
                                 L"ms.htm",
                                 L"HTTP/1.1",
                                 WINHTTP_NO_REFERER,
                                 WINHTTP_DEFAULT_ACCEPT_TYPES,
                                 0 );
  
// Exit if WinHttpOpenRequest failed.
  if( !hRequest )
    goto Exit;
  
//
// Set up the autoproxy call.
//

// Use auto-detection because the Proxy 
// Auto-Config URL is not known.
  AutoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;

// Use DHCP and 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, then automatically supply the client
// domain credentials.
  AutoProxyOptions.fAutoLogonIfChallenged = TRUE;

//
// Call WinHttpGetProxyForUrl with our target URL. If 
// auto-proxy succeeds, then set the proxy info on the 
// request handle. If auto-proxy fails, ignore the error 
// and attempt to send the HTTP request directly to the 
// target server (using the default WINHTTP_ACCESS_TYPE_NO_PROXY 
// configuration, which the requesthandle will inherit 
// from the session).
//
  if( WinHttpGetProxyForUrl( hHttpSession,
                             L"https://www.microsoft.com/ms.htm",
                             &AutoProxyOptions,
                             &ProxyInfo))
  {
  // A proxy configuration was found, set it on the
  // request handle.
    
    if( !WinHttpSetOption( hRequest, 
                           WINHTTP_OPTION_PROXY,
                           &ProxyInfo,
                           cbProxyInfoSize ) )
    {
      // Exit if setting the proxy info failed.
      goto Exit;
    }
  }

//
// Send the request.
//
  if( !WinHttpSendRequest( hRequest,
                           WINHTTP_NO_ADDITIONAL_HEADERS,
                           0,
                           WINHTTP_NO_REQUEST_DATA,
                           0,
                           0,
                           NULL ) )
  {
    // Exit if WinHttpSendRequest failed.
    goto Exit;
  }

//
// Wait for the response.
//

  if( !WinHttpReceiveResponse( hRequest, NULL ) )
    goto Exit;

//
// A response has been received, then process it.
// (omitted)
//


  Exit:
  //
  // Clean up the WINHTTP_PROXY_INFO structure.
  //
    if( ProxyInfo.lpszProxy != NULL )
      GlobalFree(ProxyInfo.lpszProxy);

    if( ProxyInfo.lpszProxyBypass != NULL )
      GlobalFree( ProxyInfo.lpszProxyBypass );

  //
  // Close the WinHTTP handles.
  //
    if( hRequest != NULL )
      WinHttpCloseHandle( hRequest );
  
    if( hConnect != NULL )
      WinHttpCloseHandle( hConnect );
  
    if( hHttpSession != NULL )
      WinHttpCloseHandle( hHttpSession );

Dans l’exemple de code fourni, l’appel à WinHttpGetProxyForUrl indique à la fonction de découvrir automatiquement le fichier de configuration automatique du proxy en spécifiant l’indicateur WINHTTP_AUTOPROXY_AUTO_DETECT dans la structure WINHTTP_AUTOPROXY_OPTIONS. L’utilisation de l’indicateur de WINHTTP_AUTOPROXY_AUTO_DETECT nécessite que le code spécifie un ou les deux indicateurs de détection automatique (WINHTTP_AUTO_DETECT_TYPE_DHCP, WINHTTP_AUTO_DETECT_TYPE_DNS_A). L’exemple de code utilise la fonctionnalité de détection automatique de WinHttpGetProxyForUrl, car l’URL PAC n’est pas connue à l’avance. Si une URL PAC ne peut pas se trouver sur le réseau dans ce scénario, WinHttpGetProxyForUrl échoue (GetLastError retourne ERROR_WINHTTP_AUTODETECTION_FAILED).

Si l’URL PAC est connue à l’avance

Si l’application connaît l’URL PAC, elle peut la spécifier dans la structure WINHTTP_AUTOPROXY_OPTIONS et configurer WinHttpGetProxyForUrl pour ignorer la phase de détection automatique.

Par exemple, si un fichier PAC est disponible sur le réseau local à l’URL , «https://InternalSite/proxy-config.pac", l’appel à WinHttpGetProxyForUrl se présente comme suit.

//
// Set up the autoproxy call.
//

// The proxy auto-config URL is known. Auto-detection
// is not required.
  AutoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;

// Set the proxy auto-config URL.
  AutoProxyOptions. lpszAutoConfigUrl =  L"https://InternalSite/proxy-config.pac";

// If obtaining the PAC script requires NTLM/Negotiate
// authentication, then automatically supply the client
// domain credentials.
  AutoProxyOptions.fAutoLogonIfChallenged = TRUE;

//
// Call WinHttpGetProxyForUrl with our target URL. If auto-proxy
// succeeds, then set the proxy info on the request handle.
// If auto-proxy fails, ignore the error and attempt to send the
// HTTP request directly to the target server (using the default
// WINHTTP_ACCESS_TYPE_NO_PROXY configuration, which the request
// handle will inherit from the session).
//
  if( WinHttpGetProxyForUrl( hHttpSession,
                             L"https://www.microsoft.com/ms.htm",
                             &AutoProxyOptions,
                             &ProxyInfo ) )
{
  //...

Si la structure WINHTTP_AUTOPROXY_OPTIONS spécifie à la fois les indicateurs WINHTTP_AUTOPROXY_AUTO_DETECT et WINHTTP_AUTOPROXY_CONFIG_URL (et spécifie les indicateurs de détction automatique et une URL de configuration automatique), WinHttpGetProxyForUrl première tentative de détection automatique, puis, si la détection automatique ne parvient pas à localiser une URL PAC, « revient » à l’URL de configuration automatique fournie par l’application.

Fonction WinHttpDetectAutoProxyConfigUrl

La fonction WinHttpDetectAutoProxyConfigUrl implémente un sous-ensemble du protocole WPAD : il tente de détecter automatiquement l’URL du fichier de configuration automatique du proxy, sans télécharger ou exécuter le fichier PAC. Cette fonction est utile dans des situations spéciales où une application cliente web doit gérer le téléchargement et l’exécution du fichier PAC lui-même.

La fonction WinHttpGetIEProxyConfigForCurrentUser

La fonction WinHttpGetIEProxyConfigForCurrentUser retourne les paramètres de proxy Internet Explorer actuels pour la connexion réseau active actuelle, sans appeler «WinInet.dll». Cette fonction est utile uniquement lorsqu’elle est appelée dans un processus qui s’exécute sous une identité de compte d’utilisateur interactive, car aucune configuration de proxy Internet Explorer n’est susceptible d’être disponible dans le cas contraire. Par exemple, il n’est pas utile d’appeler cette fonction à partir d’une DLL ISAPI exécutée dans le processus de service IIS. Pour plus d’informations et un scénario dans lequel une application WinHTTP utilise WinHttpGetIEProxyConfigForCurrentUser, consultez découverte sans fichier de configuration automatique.