Condividi tramite


Metodo IWinHttpRequest::SetCredentials

Il metodo SetCredentials imposta le credenziali da usare con un server HTTP, indipendentemente dal fatto che sia un server proxy o un server di origine.

Sintassi

HRESULT SetCredentials(
  [in] BSTR                             UserName,
  [in] BSTR                             Password,
  [in] HTTPREQUEST_SETCREDENTIALS_FLAGS Flags
);

Parametri

UserName [in]

Specifica il nome utente per l'autenticazione.

Password [in]

Specifica la password per l'autenticazione. Questo parametro viene ignorato se bstrUserName è NULL o mancante.

Flag [in]

Specifica quando IWinHttpRequest usa le credenziali. Può essere uno dei valori seguenti.

Valore Significato
HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
Le credenziali vengono passate a un server.
HTTPREQUEST_SETCREDENTIALS_FOR_PROXY
Le credenziali vengono passate a un proxy.

Valore restituito

Il valore restituito è S_OK in caso di esito positivo o di un valore di errore in caso contrario.

Commenti

Questo metodo restituisce un valore di errore se una chiamata a Open non è stata completata correttamente. Si presuppone che alcune misure di interazione con un server proxy o un server di origine debbano verificarsi prima che gli utenti possano impostare le credenziali per la sessione. Inoltre, finché gli utenti non sanno quali schemi di autenticazione sono supportati, non possono formattare le credenziali.

Nota

Per Windows XP e Windows 2000, vedere la sezione Requisiti di runtime della pagina iniziale WinHTTP.

Per eseguire l'autenticazione con sia il server che il proxy, l'applicazione deve chiamare SetCredentials due volte; prima con il parametro Flags impostato su HTTPREQUEST_SETCREDENTIALS_FOR_SERVER e secondo, con il parametro Flags impostato su HTTPREQUEST_SETCREDENTIALS_FOR_PROXY.

Esempio

Nell'esempio seguente viene illustrato come aprire una connessione HTTP, impostare le credenziali per il server, inviare una richiesta HTTP e leggere il testo della risposta. Questo esempio deve essere eseguito da un prompt dei comandi.

#include <windows.h>
#include <stdio.h>
#include <objbase.h>

#include "httprequest.h"

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")

// IID for IWinHttpRequest.
const IID IID_IWinHttpRequest =
{
  0x06f29373,
  0x5c5a,
  0x4b54,
  {0xb0, 0x25, 0x6e, 0xf1, 0xbf, 0x8a, 0xbf, 0x0e}
};

int main()
{
    // Variable for return value
    HRESULT    hr;

    // Initialize COM.
    hr = CoInitialize( NULL );

    IWinHttpRequest *  pIWinHttpRequest = NULL;

    BSTR            bstrResponse = NULL;
    VARIANT         varFalse;
    VARIANT         varEmpty;

    CLSID           clsid;

    VariantInit(&varFalse);
    V_VT(&varFalse)   = VT_BOOL;
    V_BOOL(&varFalse) = VARIANT_FALSE;

    VariantInit(&varEmpty);
    V_VT(&varEmpty) = VT_ERROR;

    hr = CLSIDFromProgID(L"WinHttp.WinHttpRequest.5.1", &clsid);

    if (SUCCEEDED(hr))
    {
        hr = CoCreateInstance(clsid, NULL,
                              CLSCTX_INPROC_SERVER,
                              IID_IWinHttpRequest,
                              (void **)&pIWinHttpRequest);
    }
    if (SUCCEEDED(hr))
    {    // Open WinHttpRequest.
        BSTR bstrMethod = SysAllocString(L"GET");
        BSTR bstrUrl = SysAllocString(L"https://microsoft.com");
        hr = pIWinHttpRequest->Open(bstrMethod, bstrUrl, varFalse);
        SysFreeString(bstrMethod);
        SysFreeString(bstrUrl);
    }
    if (SUCCEEDED(hr))
    {    // Set Credentials.
        BSTR bstrUserName = SysAllocString(L"User Name");
        BSTR bstrPassword = SysAllocString(L"Password");
        hr = pIWinHttpRequest->SetCredentials(
                               bstrUserName,
                               bstrPassword,
                               HTTPREQUEST_SETCREDENTIALS_FOR_SERVER);
        SysFreeString(bstrUserName);
        SysFreeString(bstrPassword);
    }
    if (SUCCEEDED(hr))
    {    // Send Request.
        hr = pIWinHttpRequest->Send(varEmpty);
    }
    if (SUCCEEDED(hr))
    {    // Get Response text.
        hr = pIWinHttpRequest->get_ResponseText(&bstrResponse);
    }
    if (SUCCEEDED(hr))
    {    // Print response to console.
        wprintf(L"%.256s",bstrResponse);
    }

    // Release memory.
    if (pIWinHttpRequest)
        pIWinHttpRequest->Release();
    if (bstrResponse)
        SysFreeString(bstrResponse);

    CoUninitialize();
    return 0;
}

Nell'esempio di scripting seguente viene illustrato come aprire una connessione HTTP, impostare le credenziali per il server, impostare le credenziali per un proxy se viene usato, inviare una richiesta HTTP e leggere il testo della risposta.

// HttpRequest SetCredentials flags
HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0;
HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1;

// Instantiate a WinHttpRequest object.
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");

// Specify the target resource.
var targURL = "https://msdn.microsoft.com/downloads/samples/"+
              "internet/winhttp/auth/authenticate.asp";    
WinHttpReq.open("GET", targURL, false);

var Done = false;
var LastStatus=0;
do {
    // Send a request to the server and wait for a response.                               
    WinHttpReq.send(); 
    
    // Obtain the status code from the response.
    var Status = WinHttpReq.Status;

    switch (Status){
        // A 200 status indicates that the resource was retrieved.
        case 200:
            Done = true;
            break;
                
        // A 401 status indicates that the server 
        // requires authentication.    
        case 401:
            WScript.Echo("Requires Server UserName and Password.");

            // Specify the target resource.
            WinHttpReq.open("GET", targURL, false);
                            
            // Set credentials for the server.
            WinHttpReq.SetCredentials("User Name", "Password", 
                        HTTPREQUEST_SETCREDENTIALS_FOR_SERVER);

            // If the same credentials are requested twice, abort 
            // the request.  For simplicity, this sample does not 
            // check for a repeated sequence of status codes.
            if (LastStatus==401)
                Done = true;
            break;

        // A 407 status indicates that the proxy 
        // requires authentication.    
        case 407:
            WScript.Echo("Requires Proxy UserName and Password.");
                
            // Specify the target resource.
            WinHttpReq.open("GET", targURL, false);
    
            // Set credentials for the proxy.
            WinHttpReq.SetCredentials("User Name", "Password", 
                HTTPREQUEST_SETCREDENTIALS_FOR_PROXY);

            // If the same credentials are requested twice, abort 
            // the request.  For simplicity, this sample does not 
            // check for a repeated sequence of status codes.
            if (LastStatus==407)
                Done = true;
            break;
        
        // Any other status is unexpected.
        default:
            WScript.Echo("Unexpected Status: "+Status);
            Done = true;
            break;
    }
    
    // Keep track of the last status code.
    LastStatus = Status;
    
} while (!Done);

// Display the results of the request.
WScript.Echo(WinHttpReq.Status + "   " + WinHttpReq.StatusText);
WScript.Echo(WinHttpReq.GetAllResponseHeaders());

Requisiti

Requisito Valore
Client minimo supportato
Windows XP, Windows 2000 Professional con SP3 [solo app desktop]
Server minimo supportato
Windows Server 2003, Windows 2000 Server con SP3 [solo app desktop]
Componente ridistribuibile
WinHTTP 5.0 e Internet Explorer 5.01 o versione successiva in Windows XP e Windows 2000.
IDL
HttpRequest.idl
Libreria
Winhttp.lib
DLL
Winhttp.dll

Vedi anche

IWinHttpRequest

WinHttpRequest

Versioni WinHTTP