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

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

我试着按照贴在here页上的问题go 做,但我无法正确填写属性.

我还try 将其转换为常规HTTP请求:

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

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

推荐答案

嗯,您不会直接拨打cURL,而是使用以下选项之一:

我强烈建议使用HttpClient类,因为它的设计(从可用性的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类更好地支持处理不同的响应类型,并且更好地支持异步操作(以及它们的取消).

.net相关问答推荐

如何在dotnet中使用OpenTelemetry Prometheus导出器导出多个版本的度量?

NETSDK1083:无法识别指定的 RuntimeIdentifierwin10-x64

使用 PostAsJsonAsync C# 时出现错误请求

out 和 ref 可以用作临时变量吗?

C# - 获取不包括隐藏文件的文件列表

如何从控制台应用程序中的 Task.WaitAll() 获取返回值?

maxRequestLength 的最大值?

我什么时候应该在 C# 中使用使用块?

将 Topshelf 应用程序安装为 Windows 服务

如何在 .NET 中将字符串转换为字节数组?

如何通过 LINQ 比较没有时间的 DateTime?

读取方法的属性值

变量MyException已声明但从未使用

文件按文件名模式存在

在 C#/.NET 中组合路径和文件名的最佳方法是什么?

将 Dictionary 转换为匿名对象?

为什么要使用 C# 类 System.Random 而不是 System.Security.Cryptography.RandomNumberGenerator?

Roslyn 编译代码失败

Dictionary.Add 与 Dictionary[key]=value 的区别

枚举和匹配属性的 C# 命名约定