Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata