WebRequest via HTTP with XML-Body

  • Thread starter Thread starter Kai Huener
  • Start date Start date
K

Kai Huener

Hello All,

I want to send a HttpRequest to a program running on http://localhost:8080
on my computer. I want to communicate with this programm by sending an
XML-Message and the Response will be also XML. This seams not to be very
difficult, but I cannot handle it.

How can I create such a HTTP-Connection with C#?
Are there any ideas?

Best Regards,
Kai Huener
 
Kai said:
Hello All,

I want to send a HttpRequest to a program running on
http://localhost:8080 on my computer. I want to communicate with this
programm by sending an XML-Message and the Response will be also XML.
This seams not to be very difficult, but I cannot handle it.

How can I create such a HTTP-Connection with C#?
Are there any ideas?

Kai, here's a sample method that uses the System.Net.HttpWebRequest/Response
classes. The sample assumes your XML messages should be UTF-8 encoded.

public void PostXml(string url, string xml) {
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);
}

// This sample only checks whether we get an "OK" HTTP status code back.
// If you must process the XML-based response, you need to read that from
// the response stream.
using (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,
 
in addition to the exceptional suggestion already provided, I would add that
if you simply create a web service and place it on the web site running on
that port, you will be communicating using XML over HTTP, just as you
request, with a lot more support in C# than rolling your own.

Why not just use a web service?

--- Nick
 
Back
Top