This section demonstrates how to write script that uses the WinHttpRequest object to access data from a server that requires HTTP authentication.
??? Prerequisites and Requirements ??? Accessing a Web Site With Authentication ??? Checking the Status Codes ??? Related Topics
Prerequisites and Requirements
In addition to a working knowledge of Microsoft JScript, this example requires the following:
??? The current version of the Microsoft Windows Software Development Kit (SDK). ??? The proxy configuration tool to establish the proxy settings for Microsoft Windows HTTP Services (WinHTTP), if your connection to the Internet is through a proxy server. See Proxycfg.exe, a Proxy Configuration Tool for more information. ??? A familiarity with network terminology and concepts.
Accessing a Web Site With Authentication
Aa383147.wedge(en-us,VS.85).gifTo create a script that demonstrates authentication, do the following:
??? Open a text editor such as Microsoft Notepad.
??? Copy the following code into the text editor after replacing "[authenticationSite]" with the appropriate text to specify the URL of a site that requires HTTP authentication.
??? // Load the WinHttpRequest object. ??? var WinHttpReq = ????????????? new ActiveXObject("WinHttp.WinHttpRequest.5.1");
??? function getText1( ) ??? { ????? // Specify the target resource. ????? WinHttpReq.open( "GET", ?????????????????????? "http://[authenticationSite]", ?????????????????????? false;
????? // Send a request to the server and wait for a response. ????? WinHttpReq.send( );
????? // Display the results of the request. ????? WScript.Echo( "No Credentials: " ); ????? WScript.Echo( WinHttpReq.Status + "?? " + WinHttpReq.StatusText); ????? WScript.Echo( WinHttpReq.GetAllResponseHeaders); ????? WScript.Echo( ); ??? };
????? // Set credentials for server. ????? WinHttpReq.SetCredentials( "User Name", ???????????????????????????????? "Password", ???????????????????????????????? HTTPREQUEST_SETCREDENTIALS_FOR_SERVER);
????? // It might also be necessary to supply credentials ????? // to the proxy if you connect to the Internet ????? // through a proxy that requires authentication.
????? // Send a request to the server and wait for ????? // a response. ????? WinHttpReq.send( );
??? Save the file as "Auth.js". ??? From a command prompt, type "cscript Auth.js" and press ENTER.
You now have a program that requests a resource two different ways. The first method requests the resource without supplying credentials. A 401 status code is returned to indicate that the server requires authentication. The response headers are also displayed and should look similar to the following:
Although the response indicates that access to the resource was denied, it still returns several headers that provide some information about the resource. The header named "WWW-Authenticate" indicates that the server requires authentication for this resource. If there was a header named "Proxy-Authenticate", it would indicate that the proxy server requires authentication. Each authenticate header contains an available authentication scheme and sometimes a realm. The realm value is case-sensitive and defines a set of servers or proxies for which the same credentials should be accepted.
There are two headers named "WWW-Authenticate", which indicate that multiple authentication schemes are supported. If you call the GetResponseHeader method to find "WWW-Authenticate" headers, the method only returns the contents of the first header of that name. In this case, it returns a value of "NTLM". To ensure that all occurrences of a header are processed, use the GetAllResponseHeaders method instead.
The second method call requests the same resource, but first supplies authentication credentials by calling the SetCredentials method. The following section of code shows how this method is used.
This method sets the user name to "UserName", the password to "Password", and indicates that the authorization credentials apply to the resource server. Authentication credentials can also be sent to a proxy.
When credentials are supplied, the server returns a 200 status code that indicates that the document can be retrieved. Checking the Status Codes
The previous example is instructional, but it requires that the user explicitly supply credentials. An application that supplies credentials when it is necessary and does not supply credentials when it is not necessary is more useful. To implement a feature that does this, you must modify your example to examine the status code returned with the response.
For a complete list of possible status codes, along with descriptions, see HTTP Status Codes. For this example, however, you should encounter only one of three codes. A status code of 200 indicates that a resource is available and is being sent with the response. A status code of 401 indicates that the server requires authentication. A status code of 407 indicates that the proxy requires authentication.
Modify the example you created in the last section by replacing the "getText2" function with the following code (replace "[authenticationSite]" with your own text to specifies the URL of a site that requires HTTP authentication):
function getText2() { ? WScript.Echo( "Credentials: " );
? // Specify the target resource. ? var targURL = "http://[authenticationSite]"; ? WinHttpReq.open( "GET", targURL, false );
? var Done = false; ? var Attempts = 0; ? do ? { ??? // Keep track of the number of request attempts. ??? Attempts++;
??? // 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." );
??????? // Set credentials for the server. ??????? WinHttpReq.SetCredentials( "User Name", ???????????????????????????? "Password", ????????????????????????????? HTTPREQUEST_SETCREDENTIALS_FOR_SERVER); ??????? break;
????? // A 407 status indicates that the proxy ????? // requires authentication. ????? case 407: ??????? WScript.Echo( "Requires Proxy UserName and Password." );
? // Display the results of the request. ? WScript.Echo( WinHttpReq.Status + "?? " + WinHttpReq.StatusText ); ? WScript.Echo( WinHttpReq.GetAllResponseHeaders( ) ); ? WScript.Echo( ); };
Again, save and run the file. The second method still retrieves the document, but it only provides credentials when required. The "getText2" function executes the Open and Send methods as if authentication was not required. The status is retrieved with the Status property and a switch statement responds to the resulting status code. If the status is 401 (server requires authentication) or 407 (proxy requires authentication), the Open method is executed again. This is followed by the SetCredentials method, which sets the user name and password. The code then loops back to the Send method. If, after three attempts, the resource cannot be successfully retrieved, then the function stops execution. Related Topics
Authentication in WinHTTP WinHttpRequest SetCredentials HTTP/1.1 Request for Comments (RFC 2616)
Send comments about this topic to Microsoft
Build date: 7/14/2011
--- http://www.neilstuff.com/winhttp/
I got tired of waiting for MSDN as a reference to using the WinHttp ActiveXObject, so I'm transcribing things here. Visit MSDN's WinHttpRequest Object Reference for the original content. WinHttp.WinHttpRequest.5.1 Methods of WinHttp
??? Abort: Aborts a WinHTTP Send method. ??? GetAllResponseHeaders: Retrieves all HTTP response headers. ??? GetResponseHeader: Retrieves the HTTP response headers. ??? Open: Opens an HTTP connection to an HTTP resource. ??? Send: Sends an HTTP request to an HTTP server. ??? SetAutoLogonPolicy: Sets the current Automatic Logon Policy. ??? SetClientCertificate: Selects a client certificate to send to a Secure Hypertext Transfer Protocol (HTTPS) server. ??? SetCredentials: Sets credentials to be used with an HTTP serverither an origin or a proxy server. ??? SetProxy: Sets proxy server information. ??? SetRequestHeader: Adds, changes, or deletes an HTTP request header. ??? SetTimeouts: Specifies, in milliseconds, the individual time-out components of a send/receive operation. ??? WaitForResponse: Specifies the wait time, in seconds, for an asynchronous Send method to complete, with optional time-out value.
Properties of WinHttp
??? Option: Sets or retrieves a WinHTTP option value. ??? ResponseBody: Retrieves the response entity body as an array of unsigned bytes. ??? ResponseStream: Retrieves the response entity body as an IStream. ??? ResponseText: Retrieves the response entity body as a string. ??? Status: Retrieves the HTTP status code from the last response. ??? StatusText: Retrieves HTTP status text.
Events of WinHttp
??? OnError: Occurs when there is a run-time error in the application. ??? OnResponseDataAvailable: Occurs when data is available from the response. ??? OnResponseFinished: Occurs when the response data is complete. ??? OnResponseStart: Occurs when the response data starts to be received.
WinHttp Methods GetResponseHeader The GetResponseHeader method gets the HTTP response headers.
??? Return Value = GetResponseHeader( *bstrHeader )
* = Required Syntax
??? sHeader: A value of type string that specifies the case-insensitive header name. ??? Return Value: This method returns the value of the response header named in bstrHeader.
Remarks Invoke this method only after the Send method has been called. Example The following code example shows how to open an HTTP connection, send an HTTP request, and get the date header from the response.
???? // Instantiate a WinHttpRequest object. ??? var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
??? bstrMethod: A value of type string that specifies the HTTP verb used for the Open method, such as "GET" or "PUT". Always use uppercase as some servers ignore lowercase HTTP verbs. ??? bstrUrl: A value of type string that contains the name of the resource. This must be an absolute URL. ??? varAsync: A value of type Boolean that specifies whether to open in asynchronous mode. True=Opens the HTTP connection in asynchronous mode.
Remarks This method opens a connection to the resource identified in bstrUrl using the HTTP verb given in bstrMethod. Example Code The following code example shows how to open an HTTP connection, send an HTTP request, and read the response text.
??? // Instantiate a WinHttpRequest object. ??? var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
??? // Initialize an HTTP request. ??? WinHttpReq.Open("GET", "http://www.microsoft.com", false);
??? // Send the HTTP request. ??? WinHttpReq.Send();
??? // Display the response text. ??? WScript.Echo( WinHttpReq.ResponseText);
Send() Syntax The Send method sends an HTTP request to an HTTP server.
??? Send( varBody )
??? varBody: Data to be sent to the server.
Remarks The request to be sent was defined in a prior call to the Open method. The calling application can provide data to be sent to the server through the varBody parameter. If the HTTP verb of the object's Open is "GET", this method sends the request without varBody, even if it is provided by the calling application. Example Code The following example shows how to open an HTTP connection, send an HTTP request, and read the response text.
??? // Instantiate a WinHttpRequest object. ??? var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
??? // Initialize an HTTP request. ??? WinHttpReq.Open("GET", "http://www.microsoft.com", false);
??? // Send the HTTP request. ??? WinHttpReq.Send();
??? // Display the response text. ??? WScript.Echo( WinHttpReq.ResponseText);
??? The following example shows how to post data to an HTTP server.
???? // Instantiate a WinHttpRequest object. ??? var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
??? // Initialize an HTTP request. ??? WinHttpReq.Open("PUT", "http://postserver/newdoc.htm", false);
??? // Post data to the HTTP server. ??? WinHttpReq.Send("Post data");
SetTimeouts The SetTimeouts method specifies the individual time-out components of a send/receive operation, in milliseconds. Syntax
??? ResolveTimeout: Value of type Integer integer. Time-out value applied when resolving a host name (such as www.microsoft.com) to an IP address (such as 192.168.131.199), in milliseconds. The default value is zero, meaning no time-out (infinite). If DNS timeout is specified using NAME_RESOLUTION_TIMEOUT, there is an overhead of one thread per request. ??? ConnectTimeout: Value of type Integer integer. Time-out value applied when establishing a communication socket with the target server, in milliseconds. The default value is 60,000 (60 seconds). ??? SendTimeout: Value of type Integer integer. Time-out value applied when sending an individual packet of request data on the communication socket to the target server, in milliseconds. A large request sent to an HTTP server are normally be broken up into multiple packets; the send time-out applies to sending each packet individually. The default value is 30,000 (30 seconds). ??? ReceiveTimeout: Value of type Integer integer. Time-out value applied when receiving a packet of response data from the target server, in milliseconds. Large responses are be broken up into multiple packets; the receive time-out applies to fetching each packet of data off the socket. The default value is 30,000 (30 seconds).
Remarks All parameters are required. A value of 0 or -1 sets a time-out to wait infinitely. A value greater than 0 sets the time-out value in milliseconds. For example, 30,000 would set the time-out to 30 seconds. All negative values other than -1 cause this method to fail.
Time-out values are applied at the Winsock layer.
Example The following example shows how to set all WinHTTP time-outs to 30 seconds, open an HTTP connection, and send an HTTP request.
??? // Instantiate a WinHttpRequest object. ??? var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
??? // Set time-outs. If time-outs are set, they must ??? // be set before open. ??? WinHttpReq.SetTimeouts(30000, 30000, 30000, 30000);
??? // Initialize an HTTP request. ??? WinHttpReq.Open("GET", "http://www.microsoft.com", false);
??? // Send the HTTP request. ??? WinHttpReq.Send();
WaitForResponse() The WaitForResponse method waits for an asynchronous Send method to complete, with optional time-out value, in seconds. Syntax
??? Return Value = WaitForResponse( Timeout = -1)
??? Timeout: Time-out value, in seconds. Default time-out is infinite. To explicitly set time-out to infinite, use the value -1. ??? Return Value: True=A response has been received. False=A time-out error occurred.
Remarks This method suspends execution while waiting for a response to an asynchronous request. This method should be called after a Send. Calling applications can specify an optional Timeout value, in seconds. If this method times out, the request is not aborted. This way, the calling application can continue to wait for the request, if desired, in a subsequent call to this method.
Calling this property after a synchronous Send method returns immediately and has no effect.
Example Code This example shows how to open an asynchronous HTTP connection, send an HTTP request, wait for a response, and read the response text.
???? // Instantiate a WinHttpRequest object. ??? var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
??? // Initialize an HTTP request. ??? WinHttpReq.Open("GET", "http://www.microsoft.com", true);
??? // Send the HTTP request. ??? WinHttpReq.Send();
??? // Wait for the response. ??? WinHttpReq.WaitForResponse();
??? // Display the response text. ??? WScript.Echo( WinHttpReq.ResponseText);
This topic provides information about using the WinHTTP WinHttpRequest COM object with scripting languages. Members
The WinHttpRequest object has the following types of members:
??? Events ??? Methods ??? Properties
Events
The WinHttpRequest object has the following events. Event??? Description OnError???
Occurs when there is a run-time error in the application. OnResponseDataAvailable???
Occurs when data is available from the response. OnResponseFinished???
Occurs when the response data is complete. OnResponseStart???
Occurs when the response data starts to be received.
? Methods
The WinHttpRequest object has the following methods. Method??? Description Abort???
Aborts a WinHTTP Send method. GetAllResponseHeaders???
Retrieves all HTTP response headers. GetResponseHeader???
Retrieves the HTTP response headers. Open???
Opens an HTTP connection to an HTTP resource. Send???
Sends an HTTP request to an HTTP server. SetAutoLogonPolicy???
Sets the current Automatic Logon Policy. SetClientCertificate???
Selects a client certificate to send to a Secure Hypertext Transfer Protocol (HTTPS) server. SetCredentials???
Sets credentials to be used with an HTTP server—either an origin or a proxy server. SetProxy???
Sets proxy server information. SetRequestHeader???
Adds, changes, or deletes an HTTP request header. SetTimeouts???
Specifies, in milliseconds, the individual time-out components of a send/receive operation. WaitForResponse???
Specifies the wait time, in seconds, for an asynchronous Send method to complete, with optional time-out value.
? Properties
The WinHttpRequest object has the following properties. Property??? Access type??? Description
Option ??? Read/write???
Sets or retrieves a WinHTTP option value.
ResponseBody ??? Read-only???
Retrieves the response entity body as an array of unsigned bytes.
ResponseStream ??? Read-only???
Retrieves the response entity body as an IStream.
ResponseText ??? Read-only???
Retrieves the response entity body as text.
Status ??? Read-only???
Retrieves the HTTP status code from the last response.
StatusText ??? Read-only???
Retrieves HTTP status text.
? Remarks
The WinHttpRequest object uses the IErrorInfo interface to provide error data. A description and numerical error value can be obtained with the Err object in Microsoft Visual Basic Scripting Edition (VBScript), and the Error object in Microsoft JScript. The lower 16 bits of an error number correspond to the values found in Error Messages.
Note? For Windows XP and Windows 2000, see Run-Time Requirements. Requirements
Minimum supported client ??? Windows XP, Windows 2000 Professional with SP3
Minimum supported server ??? Windows Server 2003, Windows 2000 Server with SP3
Redistributable ??? WinHTTP 5.0 and Internet Explorer 5.01 or later on Windows XP and Windows 2000.