O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.6. Communicating with a Web Server

Problem

You 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.

Solution

Use 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:

using System.Net; using System.IO; using System.Text; // ... public static HttpWebRequest GenerateGetOrPostRequest(string uriString, string method, string postData) { if((method.ToUpper( ) != "GET") && (method.ToUpper( ) != "POST")) throw new ArgumentException(method + " is not a valid method. Use GET or POST.","method"); HttpWebRequest httpRequest = null; // get a URI object Uri uri = new Uri(uriString); // create the initial request httpRequest = (HttpWebRequest)WebRequest.Create(uri); // check if asked to do a POST request, if so then modify // the original request as it defaults to a GET method if(method.ToUpper( )=="POST") { // Get the bytes for the request, should be pre-escaped byte[] bytes = Encoding.UTF8.GetBytes(postData); // Set the content type of the data being posted. httpRequest.ContentType= "application/x-www-form-urlencoded"; // Set the content length of the string being posted. httpRequest.ContentLength=postData.Length; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required