Many Web resources are protected by some sort of authentication scheme. This section examines retrieving data from Web resources that require NTLM authentication. Essentially, a NetworkCredential class needs to be created. The NetworkCredential class constructor requires a username and password in the domain. The NetworkCredential class can then be assigned to the WebRequest object that is used to perform any kind of Web request. This combination then satisfies the authentication requirements of the remote server. The code in Listing 13.5 shows how to use authentication when requesting data from a remote server. Listing 13.5 Authenticating a User Before the Data Is Retrievedtry { WebRequest req = WebRequest.Create( strURL ); NetworkCredential sc = new NetworkCredential( strUsername, strPassword, strDomain ); req.Credentials = sc; WebResponse result = req.GetResponse(); Stream ReceiveStream = result.GetResponseStream(); Encoding encode = System.Text.Encoding.GetEncoding( "utf-8" ); StreamReader sr = new StreamReader( ReceiveStream, encode ); Char[] ReadBuffer = new Char[256]; int nCount = sr.Read( ReadBuffer, 0, 256 ); while( nCount > 0 ) { String str = new String( ReadBuffer, 0, nCount ); nCount = sr.Read( ReadBuffer, 0, 256 ); } } catch( Exception ) { // Handle the exception here } |