Posting an XML to an given URL make me search google over 3 hours but at last I managed to solve the problems and successfully posted my xml.
There are some tricks like length of content, encoding of stream writer, Flush method should be called, etc. Each will be mentioned seperately.
First of all we make a web request to start a post and we will get a web response in return.
Here are our variables,
System.Net.WebRequest req = null;
System.Net.WebResponse rsp = null;
You can put the code in a try catch since you will get some undesired responses when you first try. We define the uri and then give it to webrequest as parameter.
req = System.Net.WebRequest.Create(uri);
We should provide credentials if the uri that we define will request username and password.
req.Credentials = new NetworkCredential(Username, Password);
Then we define method and content type of web request,
req.Method = "POST";
req.ContentType = "text/xml";
We should set our content length to the length of xml variable which is a string in our case. If you just use the length attribute of string then request will not be able to match the content length and actual length of xml and you will get the exception,
Bytes to be written to the stream exceed the Content-Length bytes size specified.
We should get the length with an encoding as follows,
req.ContentLength = System.Text.Encoding.UTF8.GetByteCount(xml);
After defining the length with an encoding, Stream Writer should have the same encoding too.
StreamWriter sw = new StreamWriter(req.GetRequestStream(), new UTF8Encoding(false));
Then we call write method. Until we call flush no data actually will be written to stream and without calling flush, if you close the writer you will get the error,
Webexception: The Request was aborted: The request was cancelled.
We should use the following order,
sw.Write(xml);
sw .Flush();
sw .Close();
At the end we get response and you can check which type of response is returned.
rsp = req.GetResponse();
Above code lets you post an xml file via web request to a destination Url.
Hope it helps.
P.S : If there is any typing or coding mistakes let me know. See you later.