User Id :    Password :      New Member   Forgot Password  
Programmatically creating request and handling response
Description Programmatically creating request and handling response   No. of Views     1951
  Rating     0
Author Jalpesh Vadgama   Posted On     07 Mar 2011
Tags ASP.NET    

Sample Code   Download Code

Recently one of the my friends asked about how to create a web request in to a url outside of project. So I decided to write a small blog post regarding this. This web request can be easily created with httpwebrequest class and you can easily consume the response we are getting from this. This kind of request can be very useful when you are implementing payment gateways or other third party components. Following is a code for it. It is very easy.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
namespace Experiment
   public partial class WebForm1 : System.Web.UI.Page
       protected void Page_Load(object sender, EventArgs e)
           string url = "http://localhost:1798/WebForm2.aspx";
           HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
           httpWebRequest.Method = "POST";
           httpWebRequest.ContentType = "application/x-www-form-urlencoded";
           HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
           Stream responseStream = httpWebResponse.GetResponseStream();
           StreamReader streamReader = new StreamReader(responseStream);
           string response = streamReader.ReadToEnd();

Here in the above code you can see I have created a webrequest with name space and then I have typecast that request in HttpWebRequest Class. There are several parameters are available with request like method which HTML submit method you want to use like “Get” or “Post”. After that I have created a object of HTTPResponse and then with the help of stream reader I have print a response we are getting from the URL.

That’s it. It’s very easy. Hope you will find it useful. Stay tuned for more. Happy Programming.


About Author

About Author I am jalpesh vadgama an Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having more then 5 years of experience in .NET Technology.Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible. Please also visit my blog at Jalpesh Vadgama
No Photo
Country India
Company N/A
Home Page

Rate this article

Rating options from poor, fair, good, very good to excelent.  


Write your comment here.
Verification Code