c# - 將PHP curl轉換為C#

如何將下面的php curl代碼轉換為C #代碼?


<?php


$url ="http://localhost/";


$data ="user=user1&pass=pass1";


$cookie ="00000000000000000000";


$ch = curl_init();


curl_setopt($ch, CURLOPT_URL, $url);


curl_setopt($ch, CURLOPT_POSTFIELDS, $data);


curl_setopt($ch, CURLOPT_COOKIE, $cookie);


curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);


curl_setopt($ch, CURLOPT_VERBOSE, 0);


curl_setopt($ch, CURLOPT_HEADER, 1);


$response = curl_exec($ch);


curl_close($ch);


?>



时间: 原作者:


dynamic ch = null, cookie = null, url = null, var_response = null;


 url = new XVar("http://localhost/");


 data = new XVar("user=user1&pass=pass1");


 cookie = new XVar("00000000000000000000");


 ch = XVar.Clone(CommonFunctions.curl_init());


 CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_URL), (XVar)(url));


 CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_POSTFIELDS), (XVar)(data));


 CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_COOKIE), (XVar)(cookie));


 CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_RETURNTRANSFER), new XVar(1));


 CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_VERBOSE), new XVar(0));


 CommonFunctions.curl_setopt((XVar)(ch), new XVar(Constants.CURLOPT_HEADER), new XVar(1));


 var_response = XVar.Clone(CommonFunctions.curl_exec((XVar)(ch)));


 CommonFunctions.curl_close((XVar)(ch));


 return null;



原作者:

不需要專門發出curl請求,curl在php中用作發出HTTP POST請求的簡單方法,下面應該在C#中實現同樣的功能。


var baseAddress = new Uri("http://localhost/");


var cookieContainer = new CookieContainer();


using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })


using (var client = new HttpClient(handler) { BaseAddress = baseAddress })


{


 var content = new FormUrlEncodedContent(new[]


 {


 new KeyValuePair<string, string>("user","user1"),


 new KeyValuePair<string, string>("pass","pass1"),


 });



 cookieContainer.Add(baseAddress, new Cookie("CookieName","cookie_value"));


 var result = await client.PostAsync(baseAddress, content);


 result.EnsureSuccessStatusCode();


}



原作者:
...