How post XML document using .NET?

  • Thread starter Thread starter Ronald S. Cook
  • Start date Start date
Ronald said:
What is the C# code to post a simple XML document to a URL?

This posts a string containing xml to the given url in UTF-8 encoding, and
sets the Content-Type to "text/xml". Any non-200 response is treated as an
error and an exception is thrown.

public void PostXml(string url, string xml) {
// Some serverside apps can't properly deal with Expect headers. In this
case,
// uncomment the following line.
// ServicePointManager.Expect100Continue = false;

byte[] bytes = Encoding.UTF8.GetBytes(xml);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
using (Stream requestStream = request.GetRequestStream()) {
requestStream.Write(bytes, 0, bytes.Length);
}

HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK) {
string message = String.Format("POST failed. Received HTTP {0}",
response.StatusCode);
throw new ApplicationException(message);
}
}

Cheers,
 
Back
Top