使在C#卷曲电话 [英] Making a cURL call in C#

查看:191
本文介绍了使在C#卷曲电话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想作以下卷曲呼叫我的C#控制台应用程序:

I want to make the following curl call in my C# console application:

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

我试图做类似的问题张贴此处,但我不能正确地填写属性。

I tried to do like the question posted here, but I cannot fill the properties properly.

我也试图将其转换为一个普通的HTTP请求:

I also tried to convert it to a regular HTTP request:

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

我可以转换卷曲调用一个HTTP请求?如果是这样,怎么样?如果没有,我怎么能做出上述卷曲电话从我的C#控制台应用程序正确?

Can I convert a cURL call to an HTTP request? If so, how? If not, how can I make the above cURL call from my C# console application properly?

推荐答案

好了,你不会叫卷曲直接,更确切地说,你会用下列选项之一:

Well, you wouldn't call cURL directly, rather, you'd use one of the following options:

  • <一个href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx"><$c$c>HttpWebRequest/<$c$c>HttpWebResponse
  • <一个href="http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx"><$c$c>WebClient
  • <一个href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.110%29.aspx"><$c$c>HttpClient (可从.NET 4.5)

我会强烈建议使用的HttpClient 类,因为它的设计要好得多(从可用性的角度来看),比前两者。

I'd highly recommend using the HttpClient class, as it's engineered to be much better (from a usability standpoint) than the former two.

在你的情况,你可以这样做:

In your case, you would do this:

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 类有超过$ P $处理不同的响应类型更好的支持,以及异步操作更好的支持(以及他们的取消) pviously上面提到的选项。

Also note that the HttpClient class has much better support for handling different response types, and better support for asynchronous operations (and the cancellation of them) over the previously mentioned options.

这篇关于使在C#卷曲电话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆