Recipe 14.6. Communicating with a Web ServerProblemYou want to send a request to a web server in the form of a GET or POST request. After you send the request to a web server, you want to get the results of that request (the response) from the web server. SolutionUse the HttpWebRequest class in conjunction with the WebRequest class to create and send a request to a server. Take the Uri of the resource, the method to use in the request (GET or POST), and the data to send (only for POST requests), and use this information to create an HttpWebRequest, as shown in Example 14-3. Example 14-3. Communicating with a web server
Once you have an HttpWebRequest, you send the request and get the response using the Getresponse method. It takes the newly created HttpWebRequest as input and returns an HttpWebResponse. The following example performs a GET for the index.aspx page from the http://localhost/mysite web site: HttpWebRequest request = GenerateHttpWebRequest(http://localhost/mysite/index.aspx); using(HttpWebResponse response = (HttpWebResponse) request.GetResponse( )) { // This next line uses VerifyResponse from Recipe 14.5. if(VerifyResponse(response)==ResponseCategories.Success) { Console.WriteLine("Request succeeded"); } } You generate the HttpWebRequest, send it and get the HttpWebResponse, then check the success using the VerifyResponse method from Recipe 14.5. DiscussionThe WebRequest and WebResponse classes encapsulate all of the functionality to perform basic web communications. HttpWebRequest and HttpWebResponse are derived from these classes and provide the HTTP-specific support. At the most fundamental level, to perform an HTTP-based web transaction, you use the Create method on the WebRequest class to get a WebRequest that can be cast to an HttpWebRequest (so long as the scheme is http:// or https://). This HttpWebRequest is then submitted to the web server in question when the GetResponse method is called, and it returns an HttpWebResponse that can then be inspected for the response data. See AlsoSee the "WebRequest Class," "WebResponse Class," "HttpWebRequest Class," and "HttpWebResponse Class" topics in the MSDN documentation. |