Kai Huener wrote:
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,
--
Joerg Jooss
jo*********@gmx.net