I need to call an API which accepts a POST request taking as parameter a single XML file. I've tried calling the resource via Postman (with form-data content type) and seems to work correctly. When trying to implement this in AX I get an error 500 from the server.
Here is the POST request:
void executeRequest(XmlDocument _data)
{
clrRequestObject = System.Net.WebRequest::Create("/URL/WEB/API/");
webRequest = clrRequestObject;
//Set Method Type
webRequest.set_Method("POST");
webRequest.set_CookieContainer(cookieCon);
webRequest.set_KeepAlive(true);
new InteropPermission(InteropKind::ClrInterop).assert();
// Set Content type
webRequest.set_ContentType("multipart/form-data; boundary=---------------------------7db2511d20514");
byteArray = this.getMultipartFormData(_data,"filename");
inputStream = webRequest.GetRequestStream();
inputStream.Write(byteArray, 0, byteArray.get_Length());
webResponse = webRequest.GetResponse();
inputStream.Close();
stream.Close();
webResponse.Close();
}
private System.Byte[] getMultipartFormData(XmlDocument _data, str name)
{
#define.DocFieldFormat('--\%1\r\nContent-Disposition: form-data; name=\"\%2\"; filename=\"\%3\";\r\nContent-Type: ' + '\%4\r\n\r\n')
#define.Dot('.')
System.IO.MemoryStream memstream = new System.IO.MemoryStream();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
BinData binData = new BinData();
System.Byte[] bytes;
str s;
XMLWriter xmlWriter;
str path = WinAPI::getTempPath();
Filename filename = path+name+".xml";
System.IO.FileStream fileStream;
xmlWriter = XmlWriter::newFile(filename);
_data.writeTo(XmlWriter);
xmlWriter.close();
// Header
s = strFmt(
#DocFieldFormat,
---------------------------7db2511d20514,
name,
name+#Dot+"xml",
"text/xml");
bytes = encoding.GetBytes(s);
memstream.Write(bytes, 0, bytes.get_Length());
/*Alternative attempt to set content 1*/
//binData.setStrData(_data.outerXml());
//bytes = encoding.GetBytes(binData.base64Encode());
//memstream.Write(bytes, 0, bytes.get_Length());
/*Alternative attempt to set content 2*/
//bytes = encoding.GetBytes(_data.outerXml());
//memstream.Write(bytes, 0, bytes.get_Length());
/*Alternative attempt to set content 3*/
fileStream = System.IO.File::OpenRead(filename);
fileStream.CopyTo(memstream);
}
s = "\r\n--" + #FormDataBoundary + "--\r\n";
bytes = encoding.GetBytes(s);
memstream.Write(bytes, 0, bytes.get_Length());
bytes = memstream.ToArray();
memstream.Close();
return bytes;
}
I'm looking into what the exact error is on the API server in order to help me troubleshoot but looking for any suggestions of what I might be doing wrong. Is there an alternative way of doing this via AX?