1

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.

1 Answer 1

2

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#

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.