Home > DeveloperSection > Forums > Make a post to URL and get the response
Pawan Shukla
Pawan Shukla

Total Post:29

Points:203
Posted on    November-03-2014 1:23 AM

 ASP.Net C#  Http Post 
Ratings:


 1 Reply(s)
 671  View(s)
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.



Lillian Martin

Total Post:27

Points:189
Posted on    November-03-2014 3:52 AM

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();



Don't want to miss updates? Please click the below button!

Follow MindStick