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. The WebRequest and WebResponse classes of System.Net namespace encapsulate all of the functionality to perform basic web transactions. HttpWebRequest and HttpWebResponse are derived classes from these, respectively, and provide the HTTP specific web transaction support.
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; // Get the request stream and write the post data in Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); // Done updating for POST so close the stream requestStream.Close(); } // return the request return httpRequest; }
Once we have an HttpWebRequest, we send the request and get the response using the GetResponse method that takes our newly created HttpWebRequest as input and returns an HttpWebResponse. In this example, we perform a GET for the index.aspx page from the http://localhost/mysite web site:
public enum ResponseCategories { Unknown = 0, // unknown code ( < 100 or > 599) Informational = 1, // informational codes (100 <= 199) Success = 2, // success codes (200 <= 299) Redirected = 3, // redirection code (300 <= 399) ClientError = 4, // client error code (400 <= 499) ServerError = 5 // server error code (500 <= 599) } ... public static ResponseCategories VerifyResponse(HttpWebResponse httpResponse) { // Just in case there are more success codes defined in the future // by HttpStatusCode, we will check here for the "success" ranges // instead of using the HttpStatusCode enum as it overloads some // values int statusCode = (int)httpResponse.StatusCode; if ((statusCode >= 100) && (statusCode <= 199)) { return ResponseCategories.Informational; } else if ((statusCode >= 200) && (statusCode <= 299)) { return ResponseCategories.Success; } else if ((statusCode >= 300) && (statusCode <= 399)) { return ResponseCategories.Redirected; } else if ((statusCode >= 400) && (statusCode <= 499)) { return ResponseCategories.ClientError; } else if ((statusCode >= 500) && (statusCode <= 599)) { return ResponseCategories.ServerError; } return ResponseCategories.Unknown; } ... HttpWebRequest request = GenerateGetOrPostRequest("http://localhost/mysite/index.aspx", "GET", null); HttpWebResponse response = (HttpWebResponse) request.GetResponse(); if (VerifyResponse(response) == ResponseCategories.Success) { Console.WriteLine("Request succeeded"); }
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 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.
Popularity: 6% [?]
3 Responses
abhijit
March 28th, 2007 at 1:57 pm
1if i have a page page1.aspx that will post data to page2.aspx
what should be the code for page2.aspx
should this code be written in the page_load event like
string result = “”;
string username = Request["username"];
string userpass = Request["password"];
result = “username: ” + username + ” password: ” + userpass;
System.IO.Stream newStream = new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes(result));
System.IO.StreamWriter newStreamWriter = new System.IO.StreamWriter(newStream);
HttpResponse newHttpResponse = new HttpResponse(newStreamWriter);
newHttpResponse.Write(result);
and the result returned to page1.aspx
oskar_khow
March 28th, 2007 at 5:55 pm
2hi, abhijit.
As page1.aspx will do a post to page2.aspx and expecting some returns, the page2.aspx, simply just need to return with:
Response.Write("yes, you got me. I'm page2.aspx")When page1.aspx got the response (HttpWebResponse), you can inspect the response data using the members of the class. You can have more information on HttpWebResponse at http://msdn2.microsoft.com/en-us/library/system.net.httpwebresponse_members.aspx
Hope it helps
Obtaining the HTML from a URL - Programming Tutorial On The Way
April 22nd, 2007 at 12:18 am
3[...] We can use the methods for web communication we have, VerifyResponse from Handling Web Server Errors and GenerateGetOrPostRequest from Communicating with a Web Server, to make the HTTP request and verify the response; then, we can get at the HTML via the ResponseStream property of the HttpWebResponse object: [...]
RSS feed for comments on this post · TrackBack URI
Leave a reply
Categories
Archives
Links