在 C# 中进行 cURL 调用 [英] Making a cURL call in C#

查看:62
本文介绍了在 C# 中进行 cURL 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"

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

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?

推荐答案

好吧,你不会直接调用 cURL ,而是,您可以使用以下选项之一:

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

我强烈推荐使用 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 类对处理不同的响应类型有更好的支持,并且更好地支持异步操作(和取消它们).

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# 中进行 cURL 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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