简体   繁体   中英

Trouble converting a piece of CURL to C#

I have the following CURL that I am trying to convert to C#. I have no CURL experience whatsoever.

$ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL            => 'https://api.lanoba.com/authenticate',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => array(
            'token'      => $_POST['token'],
            'api_secret' => 'YOUR-API-SECRET'
        )
    ));

Thus far I have come up with this:

//Object to create a JSON object
public class LanobaJSONObject
{
    public string token { get; set; }
    public string api_secret { get; set; }
}

public void DoAuthenticationCheck()
{


    var token = Request["token"].ToString();

        var jsonObject = new LanobaJSONObject()
        {
            token = token,
            api_secret = "YOUR-API-SECRET"
        };

        var jsonVal = Json(jsonObject, JsonRequestBehavior.AllowGet);

        Uri address = new Uri("https://api.lanoba.com/authenticate");
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
        ServicePointManager.ServerCertificateValidationCallback = delegate
        {
            return
                true; //always trust the presented cerificate
        };
        request.Method = "post";
        request.ContentType = "text/json";
        string response = null;
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(jsonVal);
        }

        using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
        {
            var reader = new StreamReader(resp.GetResponseStream());
            response = reader.ReadToEnd();
        }
//I keep getting an error code back from the provider with no real error description
//so right now I am assuming that I am doing something wrong on my end

}

Any help would be appreciated.

EDIT: FINAL ANSWER:

After the help from Onkelborg, (thank you!), here is the working example:

   var wc = new WebClient();
    var wcResponse = wc.UploadValues("https://api.lanoba.com/authenticate", new System.Collections.Specialized.NameValueCollection() { { "token", Request["token"].ToString()}, { "api_secret", "Your-Secret-Api--" } });
    var decodedResponse = wc.Encoding.GetString(wcResponse);

Once again, thank you.

As far as I can tell you shouldn't be sending JSON at all.. :)

Use the UploadStrings/UploadValues (don't remember the actual name.. :) ) on the WebClient class, it's pretty much exactly what you want - it will post a namevaluecollection to a given uri and return a string with the answer :)

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