For a project I had to post XML via a HTTP form post. Very standard stuff you would think.
We decided to do this in BizTalk since BizTalk can do this very easily. (and we were using BizTalk for most other things as well)
However somehow the HTTP post didn't work. (we got a standard HTTP error back from the third party machine)
So I tried to do the post 'manually' in C# in several ways but still without luck.
My only option left was to write custom HTTP post code and that worked!
First you must build a string according to the HTTP format.
The boundary can be everything you like as long as the receiving party uses the same boundary.
The Content-Length must be the total bytes starting from --abc and ending with --abc
Name is the reference of the XML you post used by the receiver to read the request.
Content-Type: multipart/form-data; boundary=--abc
Content-Length: 143
--abc
Content-Disposition: multipart/form-data; name="tree"; filename="yourXML.xml"
Content-Type: text/xml;
--abc
Then use this code to post it:
try
{
CookieContainer CookieJar = new CookieContainer();
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(stringURL); //stringURL is the URL to post to
Req.ContentType = "multipart/form-data; boundary=abc"; //boundary must be in line with receiving party
Req.Method = "POST";
Req.Timeout = 60000;
Req.KeepAlive = true;
Req.CookieContainer = CookieJar;
byte []Postdata = System.Text.Encoding.Default.GetBytes(stringXML); //stringXML is the XML to post
Req.ContentLength = Postdata.Length;
Stream tempStream = Req.GetRequestStream();
// write the data to be posted to the Request Stream
tempStream.Write(Postdata,0,Postdata.Length);
tempStream.Close();
HttpWebResponse Resp = (HttpWebResponse)Req.GetResponse();
//Read the raw HTML from the request
StreamReader sr = new StreamReader(Resp.GetResponseStream(), Encoding.Default);
//Convert the response stream to a string
string stringResponse = sr.ReadToEnd();
sr.Close();
Resp.Close();
return stringResponse;
}
catch (Exception e) {
throw new ApplicationException("Error posting category tree. Posted document: " + stringXML, e);
}
That's it! I still don't know why the standard .NET functions didn't work but the above code is exactly according official HTTP standards.
Posted
Thu, Jan 20 2005 11:17 AM
by
Fijsjan Heijkoop