MAKE A POST TO URL AND GET THE RESPONSE

Pawan Shukla

Total Post:29

Points:203
Posted by  Pawan Shukla
 899  View(s)
Ratings:
Rate this:

I try to post an XML file to the url and get the response back. I have this code to post. I am not really sure how to check if it is posting correctly and how to get the response.

WebRequest req = null;
            WebResponse rsp = null;
          //  try
          //  {
                string fileName = @"C:\ApplicantApproved.xml";
                string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
                req = WebRequest.Create(uri);

                req.Method = "POST";        // Post method
                req.ContentType = "text/xml; encoding='utf-8'";

                // Wrap the request stream with a text-based writer
                StreamWriter writer = new StreamWriter(req.GetRequestStream());
                // Write the XML text into the stream
                writer.WriteLine(this.GetTextFromXMLFile(fileName));
                writer.Close();
                // Send the data to the webserver
                rsp = req.GetResponse();

I think I should have response in rsp but I am not seeing anything usufull on it.

  1. Lillian Martin

    Post:27

    Points:189
    Re: Make a post to URL and get the response

    Please try following.

    WebRequest req = null;
    string fileName = @"C:\ApplicantApproved.xml";
    string uri = "http://stage.test.com/partners/wp/ajax/consumeXML.php";
    req = WebRequest.Create(uri);
    
    req.Method = "POST";        // Post method
    req.ContentType = "text/xml; encoding='utf-8'";
    
    // Write the XML text into the stream
    byte[] byteArray = Encoding.UTF8.GetBytes(this.GetTextFromXMLFile(fileName));
    
    // Set the ContentLength property of the WebRequest.
    req.ContentLength = byteArray.Length;
    // Get the request stream.
    Stream dataStream = req.GetRequestStream();
    // Write the data to the request stream.
    dataStream.Write(byteArray, 0, byteArray.Length);
    // Close the Stream object.
    dataStream.Close();
    
    WebResponse response = req.GetResponse();
    // Display the status.
    Console.WriteLine(((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.
    Console.WriteLine(responseFromServer);
    // Clean up the streams.
    reader.Close();
    dataStream.Close();
    response.Close();


Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!