2012-07-11 40 views
0

我試圖將CURL轉換爲CURL。我沒有任何CURL經驗。將一塊CURL轉換爲C時遇到麻煩#

$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' 
     ) 
    )); 

到目前爲止,我想出了這一點:

//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 

} 

任何幫助,將不勝感激。

編輯:最後的答案:

從Onkelborg的幫助後,(謝謝!),這裏是工作示例:

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); 

再次感謝你。

回答

1

至於我可以告訴你不應該在所有被髮送JSON .. :)

上WebClient類使用UploadStrings/UploadValues(不記得實際名稱.. :))它幾乎正是你想要的 - 它會發布namevalue集合到給定的uri並返回一個字符串與答案:)

+0

你說得對,謝謝。結果如下。 var wc = new WebClient(); var wcResponse = wc.UploadValues(「https://api.lanoba.com/authenticate」,new System.Collections.Specialized.NameValueCollection(){{token「,Request [」token「]。ToString()}, {「api_secret」,「My-Secret-API--」}}); var decodedResponse = wc.Encoding.GetString(wcResponse); – Ryk 2012-07-11 23:20:18