0
Reply

Post data to a website an get back the response from the server

zohaib

zohaib

Apr 19 2012 3:11 AM
1.2k
i am trying to post a data to a website and get the response back from the server. Instead of getting the reply back from the server, i am getting redirected to the same webpage in which i am posting the data. Please help me if anyone has got any idea as what has gone wrong with my code. I've been trying since long back but all efforts went in vain. The code that i am using is this.


 // Create a request using a URL that can receive a post.
  WebRequest request = WebRequest.Create("http://www.indianrail.gov.in/train_Schedule.html");
  ((HttpWebRequest)request).UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:9.0) Gecko/20100101 Firefox/9.0";
  // Set the Method property of the request to POST.
  request.Method = "POST";
  // Create POST data and convert it to a byte array.
  string postData = lccp_trnname.Text;
  byte[] byteArray = Encoding.UTF8.GetBytes(postData);
  // Set the ContentType property of the WebRequest.
  request.ContentType = "application/x-www-form-urlencoded";
  // Set the ContentLength property of the WebRequest.
  request.ContentLength = byteArray.Length;
  // Get the request stream.
  Stream dataStream = request.GetRequestStream();
  // Write the data to the request stream.
  dataStream.Write(byteArray, 0, byteArray.Length);
  // Close the Stream object.
  dataStream.Close();
  // Get the response.
  try
  {
  WebResponse response = request.GetResponse();
  // Display the status.
  Response.Write(((HttpWebResponse)response).StatusDescription);
  // Get the stream containing content returned by the server.
  dataStream = response.GetResponseStream();
  // Open the stream using a StreamReader for easy access.
  StreamReader reader = new StreamReader(dataStream);
  // Read the content.
  string responseFromServer = reader.ReadToEnd();
  // Display the content.
  Response.Write(responseFromServer);
  // Clean up the streams.
  reader.Close();
  dataStream.Close();
  response.Close();
  }
  catch (WebException ee)
  {
  Label1.Text = ee.Message;

  }