Search code examples
c#phpweb-serviceshttp-headershttpwebrequest

HTTP Post with Header Fields and XML data in C#


I am new to C# and i want to post a HTTP request to one specific URL along with the HTTP Headers and some XML data. I am having its PHP code but i don't know how to write the same in C#. My PHP code is as bellow.


$url ="https://datasend.getdata.com";
$session= $_REQUEST["session"];
$token= $_REQUEST["token"];

$XPost ="<ENVELOPE>
<HEADER>
<VERSION>1</VERSION>
<REQVERSION>1</REQVERSION>
<TALLYREQUEST>EXPORT</TALLYREQUEST>
<TYPE>DATA</TYPE>
<ID>TPGETCOMPANIES</ID>
<SESSIONID>$session</SESSIONID>
<TOKEN>$token</TOKEN>
</HEADER>
<BODY>
<DESC>
<STATICVARIABLES>
<SVINCLUDE>CONNECTED</SVINCLUDE>
</STATICVARIABLES>
</DESC>
</BODY>
</ENVELOPE>";

$headers = array();
$headers[] = 'ID:TPGETCOMPANIES';
$headers[] = 'SOURCE:MAZENETTECH';
$headers[] = 'TARGET: TNS';
$headers[] = 'CONTENT-TYPE:text/xml;charset=utf-8';
$headers[] = 'Accept-Encoding:identity';

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_TIMEOUT, 40); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_POSTFIELDS, $XPost); 
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch); 


echo($result);

Solution

  • If you search there are so many answers on SO as well as other communities.

    HTTP post XML data in C#

    And much more.

    You can add predefined headers as well as custom header using the Request.Headers property.