在C#中调用cURL

我想在我的C#控制台应用程序中进行下面的curl调用:

curl -d "text=This is a block of text" http://api.repustate.com/v2/demokey/score.json 

我试图像这里发布的问题,但我不能正确填写属性。

我也尝试将其转换为常规的HTTP请求:

 http://api.repustate.com/v2/demokey/score.json?text="This%20is%20a%20block%20of%20text" 

我可以将cURL调用转换为HTTP请求吗? 如果是这样,怎么样? 如果没有,我怎样才能正确地从我的C#控制台应用程序进行上述cURL调用?

那么,你不会直接调用cURL ,而是使用以下选项之一:

  • HttpWebRequest / HttpWebResponse
  • WebClient
  • HttpClient (可从.NET 4.5开始)

我强烈build议使用HttpClient类,因为它被devise得比前两个好(从可用性的angular度来看)。

在你的情况下,你会这样做:

 using System.Net.Http; var client = new HttpClient(); // Create the HttpContent for the form to be posted. var requestContent = new FormUrlEncodedContent(new [] { new KeyValuePair<string, string>("text", "This is a block of text"), }); // Get the response. HttpResponseMessage response = await client.PostAsync( "http://api.repustate.com/v2/demokey/score.json", requestContent); // Get the response content. HttpContent responseContent = response.Content; // Get the stream of the content. using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync())) { // Write the output. Console.WriteLine(await reader.ReadToEndAsync()); } 

另请注意, HttpClient类更好地支持处理不同的响应types,并且更好地支持asynchronous操作(以及取消它们)在前面提到的选项上。

以下是一个工作示例代码。

请注意,您需要添加对Newtonsoft.Json.Linq的引用

 string url = "https://yourAPIurl" WebRequest myReq = WebRequest.Create(url); string credentials = "xxxxxxxxxxxxxxxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; CredentialCache mycache = new CredentialCache(); myReq.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials)); WebResponse wr = myReq.GetResponse(); Stream receiveStream = wr.GetResponseStream(); StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8); string content = reader.ReadToEnd(); Console.WriteLine(content); var json = "[" + content + "]"; // change this to array var objects = JArray.Parse(json); // parse as array foreach (JObject o in objects.Children<JObject>()) { foreach (JProperty p in o.Properties()) { string name = p.Name; string value = p.Value.ToString(); Console.Write(name + ": " + value); } } Console.ReadLine(); 

参考: TheDeveloperBlog.com

还是在rest夏普 :

 var client = new RestClient("https://example.com/?urlparam=true"); var request = new RestRequest(Method.POST); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("cache-control", "no-cache"); request.AddHeader("header1", "headerval"); request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody); IRestResponse response = client.Execute(request);