2012-07-11 43 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