I am posting to an API that seems to insist on receiving XML data as multipart/form-data. The request works in SOAP UI. But, fails in c#. Below is the code submitted based on https://technet.rapaport.com/Info/LotUpload/SampleCode/Full_Example.aspx
string url = string.Format("url");
string strTkn = "strTkn";
string hdrXml = string.Format("<?xml version=\"1.0\" ?>\n<importdata>\n --redacted-XML-- \n</importdata>");
WebRequest request = WebRequest.Create(url);
request.Headers.Add("Authorization", "Bearer " + strTkn);
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
string formContentType = "multipart/form-data; boundary=" + boundary;
request.ContentType = formContentType;
request.Method = "POST";
Stream postDataStream = new System.IO.MemoryStream();
string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +
"Content-Disposition: form-data; name=\"xml\"; filename=\"request\"" +
Environment.NewLine + "Content-Type: text/xml" + Environment.NewLine + Environment.NewLine;
byte[] byteHdr = System.Text.Encoding.UTF8.GetBytes(fileHeaderTemplate);
byte[] byteEnd = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "--");
byte[] byteArray = System.Text.UTF8Encoding.UTF8.GetBytes(hdrXml);
postDataStream.Write(byteHdr, 0, byteHdr.Length);
postDataStream.Write(byteArray, 0, byteArray.Length);
postDataStream.Write(byteEnd, 0, byteEnd.Length);
postDataStream.Position = 0;
byte[] buffer = new byte[1024];
int bytesRead = 0;
request.ContentLength = postDataStream.Length;
Stream reqStream = request.GetRequestStream();
while ((bytesRead = postDataStream.Read(buffer, 0, buffer.Length)) != 0)
{
reqStream.Write(buffer, 0, bytesRead);
}
postDataStream.Close();
reqStream.Close();
StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream());
string Result = sr.ReadToEnd();
A MIME attachment starts with two dashes at the beginning of a new line. See: https://docs.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/aa563375(v=exchg.140)
You have an extra line starting with two dashes
Here is your MIME attachment
------------------------------8d90d21ca8659b4 Content-Disposition: form-data; name="xml"; filename="request" Content-Type: text/xml
------------------------------8d90d21ca8659b4--
byteArray: Below the two dashes do not start at beginning of new line.
<?xml version="1.0"?> <importdata> --redacted-XML-- </importdata>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.