如何将帖子发送到URL并获得响应

时间:2014-10-10 02:13:47

标签: c# asp.net post http-post

我尝试将XML文件发布到url并获取响应。我有这个代码发布。我不确定如何检查它是否正确发布以及如何获得响应。

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

我想我应该在rsp中有回应,但我没有看到任何有用的东西。

2 个答案:

答案 0 :(得分:0)

req.ContentType = "application/xml";

答案 1 :(得分:0)

请尝试以下。

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