Condividi tramite


Funzioni WinHTTP AutoProxy

WinHTTP implementa il protocollo WPAD usando la funzione WinHttpGetProxyForUrl insieme a due funzioni di utilità di supporto, WinHttpDetectAutoProxyConfigUrl e WinHttpGetIEProxyConfigForCurrentUser.

Il supporto di AutoProxy non è completamente integrato nello stack HTTP in WinHTTP. Prima di inviare una richiesta, l'applicazione deve chiamare WinHttpGetProxyForUrl per ottenere il nome di un server proxy e quindi chiamare WinHttpSetOption usando WINHTTP_OPTION_PROXY per impostare la configurazione proxy nell'handle di richiesta WinHTTP creato da WinHttpOpenRequest.

La funzione WinHttpGetProxyForUrl può eseguire tutti e tre i passaggi del protocollo WPAD descritti nella panoramica precedente: (1) individuare l'URL PAC, (2) scaricare il file di script PAC, (3) eseguire il codice script e restituire la configurazione del proxy in una struttura WINHTTP_PROXY_INFO . Facoltativamente, se l'applicazione conosce in anticipo l'URL PAC che può specificare questa opzione in WinHttpGetProxyForUrl.

Il codice di esempio seguente usa autoproxy. Configura una richiesta HTTP GET creando prima di tutto la connessione alla sessione WinHTTP e agli handle delle richieste. La chiamata WinHttpOpen specifica WINHTTP_ACCESS_TYPE_NO_PROXY per la configurazione del proxy iniziale, per indicare che le richieste vengono inviate direttamente al server di destinazione per impostazione predefinita. Usando autoproxy, imposta quindi la configurazione del proxy direttamente nell'handle della richiesta.

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

Nel codice di esempio fornito, la chiamata a WinHttpGetProxyForUrl indica alla funzione di individuare automaticamente il file di configurazione automatica del proxy specificando il flag di WINHTTP_AUTOPROXY_AUTO_DETECT nella struttura WINHTTP_AUTOPROXY_OPTIONS . L'uso del flag di WINHTTP_AUTOPROXY_AUTO_DETECT richiede che il codice specifichi uno o entrambi i flag di rilevamento automatico (WINHTTP_AUTO_DETECT_TYPE_DHCP, WINHTTP_AUTO_DETECT_TYPE_DNS_A). Il codice di esempio usa la funzionalità di rilevamento automatico di WinHttpGetProxyForUrl perché l'URL PAC non è noto in anticipo. Se non è possibile trovare un URL PAC nella rete in questo scenario, WinHttpGetProxyForUrl ha esito negativo (GetLastError restituisce ERROR_WINHTTP_AUTODETECTION_FAILED).

Se l'URL PAC è noto in anticipo

Se l'applicazione conosce l'URL PAC, può specificarla nella struttura WINHTTP_AUTOPROXY_OPTIONS e configurare WinHttpGetProxyForUrl per ignorare la fase di rilevamento automatico.

Se, ad esempio, un file PAC è disponibile nella rete locale all'URL "https://InternalSite/proxy-config.pac", la chiamata a WinHttpGetProxyForUrl dovrebbe essere visualizzata di seguito.

//
// 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 ) )
{
  //...

Se la struttura WINHTTP_AUTOPROXY_OPTIONS specifica sia flag di WINHTTP_AUTOPROXY_AUTO_DETECT che di WINHTTP_AUTOPROXY_CONFIG_URL (e specifica flag di detzione automatica e un URL di configurazione automatica), WinHttpGetProxyForUrl tenta innanzitutto il rilevamento automatico e quindi, se il rilevamento automatico non riesce a individuare un URL PAC, "torna" all'URL di configurazione automatica fornito dall'applicazione.

Funzione WinHttpDetectAutoProxyConfigUrl

La funzione WinHttpDetectAutoProxyConfigUrl implementa un subset del protocollo WPAD: tenta di rilevare automaticamente l'URL per il file di configurazione automatica del proxy, senza scaricare o eseguire il file PAC. Questa funzione è utile in situazioni speciali in cui un'applicazione client Web deve gestire il download e l'esecuzione del file PAC stesso.

Funzione WinHttpGetIEProxyConfigForCurrentUser

La funzione WinHttpGetIEProxyConfigForCurrentUser restituisce le impostazioni proxy dell'utente corrente di Internet Explorer per la connessione di rete attiva corrente, senza chiamare in "WinInet.dll". Questa funzione è utile solo quando viene chiamato all'interno di un processo in esecuzione in un'identità dell'account utente interattivo, perché è probabile che non sia disponibile alcuna configurazione proxy di Internet Explorer in caso contrario. Ad esempio, non sarebbe utile chiamare questa funzione da una DLL ISAPI in esecuzione nel processo del servizio IIS. Per altre informazioni e uno scenario in cui un'applicazione basata su WinHTTP userebbe WinHttpGetIEProxyConfigForCurrentUser, vedere Individuazione senza un file di configurazione automatica.