ASP.NET 2.0 (C#) Send Request via HTTP and get response

Posted by themamakcorner January - 5 - 2011 1 Comment

Following is the example to send a request via HTTP and then get the response.

Here’s how you can test using Visual Studio Express 2010

(1) Create  a WebApplication

File –> New Project

(2) Drag a Label to the Default.aspx (so that we can see the output later)

(3) At Default.aspx.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Text;

namespace TestWebApplication
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String responseStr = “”;
try
{
// Create a request that can receive a POST
WebRequest request = WebRequest.Create(“http://www.facebook.com”);
// Set Method request to POST
request.Method = “POST”;
string postData = “Testing Testing 123″;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set ContentType property of the WebRequest
request.ContentType = “application/x-www-form-urlencoded”;
// If required, Set valid User-Agent
//request.Headers.Add(“HTTP_USER_AGENT”, “Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13″);
// Set ContentLength
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// Get response
WebResponse response = request.GetResponse();
// Display status
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read content
string responseFromServer = reader.ReadToEnd();
// Get content
responseStr = responseFromServer;
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
//Catch exception
responseStr = ex.Message;
}
//Set the response to Label1 so that we can see the output
Label1.Text = responseStr;
}
}
}

(4) Build & Run the project

Related Posts Plugin for WordPress, Blogger...

One Response so far.

  1. maverick says:

    nice! very simple and easy :)