Programmatically creating asp.net request and handling response

  • 4

Recently one of the my friends asked about how to create a web request in asp.net 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();

Response.Write(Response);
}
}
}
Here in the above code you can see I have created a webrequest with system.net 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..

Technorati Tags: ,,,
Shout it

4 comments:

  1. Thanks for sharing this code, I was in search of this code since from long time. Now I would like to try to practically implement this.

    ReplyDelete
  2. your site makes 100% CPU usage ... reconsider your theme and scripts ...

    ReplyDelete
  3. Can you tell How to create a social account from out website using ASP.net

    ReplyDelete
  4. It is very help full thanks

    ReplyDelete

Your feedback are very important to me. Please provide your feedback via putting comments.