tags:

views:

61

answers:

1

Can anyone help? I have a PHP method that sends an http post:

<?php
// API URL
$api_url = "url_of_the_API ";
// Apache auth
$api_user = "user";
$api_pass = "pass";
// Request
$xml = "";
$context = stream_context_create(
array (
'http' => array(
'method' => 'POST',
'header' => sprintf("Authorization: Basic %s\r\n",
base64_encode($api_user.':'.$api_pass))
."Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query(array('xml' => $xml)),
'timeout' => 5,
),
)
);
$response = file_get_contents($api_url,false,$context);
header ("Content-Type:text/xml");
echo $response;
?>

I need to translate this to C# and I am getting a reply back from the webservice saying "POST call with XML required". I am being told that:

"the XML is not being sent via POST in the 'xml' (name) variable? This is a similar process to submitting a webform with one variable called 'xml'."

Below is my C#

        // this is where we will send it
        const string uri = "theUri";

        // create a request
        var request = (HttpWebRequest)
        WebRequest.Create(uri); request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;
        request.Method = "POST";
        request.Credentials = new NetworkCredential("theUserName", "thePassword");

        // turn our request string into a byte stream
        var postBytes = Encoding.ASCII.GetBytes(postData);

        // this is important - make sure you specify type this way
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postBytes.Length;
        var requestStream = request.GetRequestStream();

        // now send it
        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();

        // grab te response and print it out to the console along with the status code
        var response = (HttpWebResponse)request.GetResponse();
        Console.WriteLine(new StreamReader(response.GetResponseStream()).ReadToEnd());
        Console.WriteLine(response.StatusCode);
+2  A: 

Just as the error message says, you need to prepend xml= to your postData (just before converting it to bytes). In other words, your C# code skips this step:

$postdata = http_build_query(array('xml' => $xml))

and does this instead:

$postdata = $xml;

(In such cases, it has always helped me to set up Wireshark/tshark/tcpdump on either of the connection endpoints (in this case, probably on your server) and then compare the HTTP requests made by the two scripts. It's easy to notice the differences that way.)

Piskvor