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.Http WebRequest/Response
classes. The sample assumes your XML messages should be UTF-8 encoded.
public void PostXml(string url, string xml) {
byte[] bytes = Encoding.UTF8.G etBytes(xml);
HttpWebRequest request = (HttpWebRequest ) WebRequest.Crea te(url);
request.Method = "POST";
request.Content Length = bytes.Length;
request.Content Type = "text/xml";
using (Stream requestStream = request.GetRequ estStream()) {
requestStream.W rite(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 (HttpWebRespons e response = (HttpWebRespons e) request.GetResp onse())
{
if (response.Statu sCode != HttpStatusCode. OK) {
string message = String.Format(
"POST failed. Received HTTP {0}",
response.Status Code);
throw new ApplicationExce ption(message);
}
}
}
Cheers,
--
Joerg Jooss
jo*********@gmx .net