简体   繁体   中英

PHP Curl to C# Webclient/HTTPRequest

I'm trying to convert the following to C# without much luck.

<?php
$data = '<xml>my xml request here</xml>';
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "http://myendpoint");
curl_setopt($tuCurl, CURLOPT_PORT , 443);
curl_setopt($tuCurl, CURLOPT_VERBOSE, 0);
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_POST, 1);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml","SOAPAction: \"/soap/action/query\"", "Content-length: ".strlen($data)));

Below is what I've come up with but I'm not receiving the expected result. Is there something I'm simply missing in my C# ?

    using (var client = new System.Net.WebClient())
    {
        var data = new NameValueCollection();
        data.Add("", "my xml here");

        var result = client.UploadValues("my endpoint here", data);

        var str = Encoding.UTF8.GetString(result);
    }

FYI I figured this out with the following code snippet:

    public static string POST(string url, string requestXML)
    {
        WebRequest webReq = HttpWebRequest.Create(url);
        webReq.ContentType = "application/x-www-form-urlencoded";
        webReq.Method = "POST";

        using (var stream = webReq.GetRequestStream())
        {
            var arrBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(requestXML);
            stream.Write(arrBytes, 0, arrBytes.Length);
            stream.Close();
        }

        WebResponse webResp = webReq.GetResponse();
        var respStream = webResp.GetResponseStream();
        var reader = new StreamReader(respStream, System.Text.Encoding.ASCII);
        string strResponse = reader.ReadToEnd();
        respStream.Close();

        return strResponse;
    }

http://vh4u.blogspot.com/2015/02/using-dhl-web-services-in-your-net.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM