I have below curl request that I want to convert to C# code. I'm just not sure what is the equivalent of "--data-binary" in HttpWebRequest.
curl -s -H "Content-Type:application/xml" -X POST --data-binary @C:\path\to\file.xml "https://somerestURL?create"
So far, below is my code:
var xmlFile = "C:\\path\\to\\file.xml";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
NetworkCredential cred = new NetworkCredential(uname, cipher);
CredentialCache cache = new CredentialCache { { url, "Basic", cred } };
request.PreAuthenticate = true;
request.Credentials = cache;
request.Method = "POST";
request.ContentType = "application/xml";
I can provide information if you need more. Thank you.
I focused on searching conversion/equivalent of curl to c# code but it got me no luck. So, I researched about XML POSTING and below is my working code.
// initiate xml
XmlDocument xml = new XmlDocument();
xml.Load(xmlFile);
byte[] bytes = Encoding.ASCII.GetBytes(xml.InnerXml);
// setup request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
NetworkCredential cred = new NetworkCredential(uname, cipher);
CredentialCache cache = new CredentialCache { { url, "Basic", cred } };
request.PreAuthenticate = true;
request.Credentials = cache;
request.Method = "POST";
request.ContentType = "application/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
// stream
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
// response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(responseStream, Encoding.Default);
var xmlResponse = readStream.ReadToEnd();
I got my idea from this post and changed a bit based on my requirement: HTTP post XML data in C#