CaptnCrash CaptnCrash - 1 year ago 84
C# Question

Need help with HttpWebRequest on a Compact Framework Project

not so long ago I´ve created a small iphone app for my Daily use. Now I want to port this app to a Windows Mobile Device while using C# and the Compact Framework. But I really have no clue how to use the HttpWebRequest and the msdn doesn´t help me either. I think I have a lag of understanding on how Web Requests work in general.

In the iPhone app I have the following lines code:

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]];
[theRequest setHTTPMethod:@"POST"];
[theRequest addValue:@"text/xml" forHTTPHeaderField:@"content-type"];
[theRequest setCachePolicy:NSURLCacheStorageNotAllowed];
[theRequest setTimeoutInterval:5.0];
NSString* pStr = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>xxx.SessionInitiate</methodName><params><param><value><struct><member><name>LocalUri</name><value><string></string></value></member><member><name>RemoteUri</name><value><string>xxxx</string></value></member><member><name>TOS</name><value><string>text</string></value></member><member><name>Content</name><value><string>%@</string></value></member><member><name>Schedule</name><value><string></string></value></member></struct></value></param></params></methodCall>", number.text, TextView.text];
NSData* pBody = [pStr dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:pBody];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

The Webservice has no wsdl so I have to use the HttpWebRquest Object in .Net CF.
What I didn´t get is, where to put the Body (the long XML) in my Request?

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"");
req.Method = @"POST";
req.ContentType = @"test/xml";
req.Timeout = 5;

I started this way, is the first line it´s own HttpWebRequest and for the XML Body I have to create anotherone?! How do I use it correctly, how do I send it? Sorry if this might be normaly totaly easy but I really don´t get it. I´ve searched the web, 2 Books and the msdn but in every tutorial is only a Webrequest with an URL but without a body.

Thank you


Answer Source

You need to write the POST data to the request stream.

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"");
req.Method = "POST";
req.ContentType = "test/xml";
req.Timeout = 5;
using (Stream stream = req.GetRequestStream())
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
    writer.Write("PUT THE XML HERE");

using (StreamReader reader = req.GetResponse().GetResponseStream())
    string result = reader.ReadToEnd();