How do I POST XML data with curl

HttpPostCurl

Http Problem Overview


I want to post XML data with cURL. I don't care about forms like said in https://stackoverflow.com/questions/84619/how-do-i-make-a-post-request-with-curl">How do I make a post request with curl.

I want to post XML content to some webservice using cURL command line interface. Something like:

curl -H "text/xml" -d "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/

The above sample however cannot be processed by the service.


Reference example in C#:

WebRequest req = HttpWebRequest.Create("http://myapiurl.com/service.svc/");
req.Method = "POST";
req.ContentType = "text/xml";
using(Stream s = req.GetRequestStream())
{
    using (StreamWriter sw = new StreamWriter(s))
        sw.Write(myXMLcontent);
}
using (Stream s = req.GetResponse().GetResponseStream())
{
    using (StreamReader sr = new StreamReader(s))
        MessageBox.Show(sr.ReadToEnd());
}

Http Solutions


Solution 1 - Http

-H "text/xml" isn't a valid header. You need to provide the full header:

-H "Content-Type: text/xml" 

Solution 2 - Http

I prefer the following command-line options:

cat req.xml | curl -X POST -H 'Content-type: text/xml' -d @- http://www.example.com

or

curl -X POST -H 'Content-type: text/xml' -d @req.xml http://www.example.com

or

curl -X POST -H 'Content-type: text/xml'  -d '<XML>data</XML>' http://www.example.com 

Solution 3 - Http

It is simpler to use a file (req.xml in my case) with content you want to send -- like this:

curl -H "Content-Type: text/xml" -d @req.xml -X POST http://localhost/asdf

You should consider using type 'application/xml', too (differences explained here)

Alternatively, without needing making curl actually read the file, you can use cat to spit the file into the stdout and make curl to read from stdout like this:

cat req.xml | curl -H "Content-Type: text/xml" -d @- -X POST http://localhost/asdf

Both examples should produce identical service output.

Solution 4 - Http

Have you tried url-encoding the data ? cURL can take care of that for you :

curl -H "Content-type: text/xml" --data-urlencode "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/

Solution 5 - Http

You can try the following solution:

curl -v -X POST -d @payload.xml https://<API Path> -k -H "Content-Type: application/xml;charset=utf-8"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJan JongboomView Question on Stackoverflow
Solution 1 - HttpBen JamesView Answer on Stackoverflow
Solution 2 - Httpstones333View Answer on Stackoverflow
Solution 3 - Httpdk1844View Answer on Stackoverflow
Solution 4 - HttpFrançois FeugeasView Answer on Stackoverflow
Solution 5 - HttpAnkur TadeView Answer on Stackoverflow