在C#中进行cURL调用


88

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

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调用?



@DanielEarwicker:我会说这是不是,只是因为HttpClient是在搭配现在,这将是方式完胜HTTP内容HttpWebRequestWebClient前进。
casperOne

Answers:


146

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

我强烈建议使用HttpClient该类,因为从可用性的角度出发,它比前两个要好得多。

对于您的情况,您可以这样做:

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与前面提到的选项相比,该类对处理不同的响应类型有更好的支持,并且对异步操作(以及取消它们)有更好的支持。


7
我曾尝试按照您的代码处理类似的问题,但系统却提示我只能设置为异步方法的错误?
杰伊

@Jay是的,async和await是一对,没有另一个就不能使用。这意味着您必须使包含方法(此处没有该方法)异步。
casperOne 2013年

1
@Jay其中大多数方法return Task<T>,您不能正常使用async然后再处理返回类型(必须调用Task<T>.Result。注意,async尽管浪费线程等待结果,但最好还是使用)。
casperOne 2013年

1
@Maxsteel是的,它是一个数组,KeyValuePair<string, string>所以您只需使用new [] { new KeyValuePair<string, string>("text", "this is a block of text"), new KeyValuePair<string, string>("activity[verb]", "testVerb") }
casperOne'1

1
这样可以打电话吗?curl -k -i -H "Accept: application/json" -H "X-Application: <AppKey>" -X POST -d 'username=<username>&password=<password>' https://identitysso.betfair.com/api/login
Murray Hart

24

或在restSharp中

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);

1
基本用法示例无法立即使用。restSharp是垃圾。
Alex G

1
@AlexG您当时做错了。为我工作。
user2924019

13

下面是一个有效的示例代码。

请注意,您需要添加对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


2

反应迟到,但这就是我最终要做的。如果要在Linux上运行curl命令时非常类似地运行curl命令,并且您拥有Windows 10或更高版本,请执行以下操作:

    public static string ExecuteCurl(string curlCommand, int timeoutInSeconds=60)
    {
        if (string.IsNullOrEmpty(curlCommand))
            return "";

        curlCommand = curlCommand.Trim();

        // remove the curl keworkd
        if (curlCommand.StartsWith("curl"))
        {
            curlCommand = curlCommand.Substring("curl".Length).Trim();
        }

        // this code only works on windows 10 or higher
        {

            curlCommand = curlCommand.Replace("--compressed", "");

            // windows 10 should contain this file
            var fullPath = System.IO.Path.Combine(Environment.SystemDirectory, "curl.exe");

            if (System.IO.File.Exists(fullPath) == false)
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Windows 10 or higher is required to run this application");
            }

            // on windows ' are not supported. For example: curl 'http://ublux.com' does not work and it needs to be replaced to curl "http://ublux.com"
            List<string> parameters = new List<string>();


            // separate parameters to escape quotes
            try
            {
                Queue<char> q = new Queue<char>();

                foreach (var c in curlCommand.ToCharArray())
                {
                    q.Enqueue(c);
                }

                StringBuilder currentParameter = new StringBuilder();

                void insertParameter()
                {
                    var temp = currentParameter.ToString().Trim();
                    if (string.IsNullOrEmpty(temp) == false)
                    {
                        parameters.Add(temp);
                    }

                    currentParameter.Clear();
                }

                while (true)
                {
                    if (q.Count == 0)
                    {
                        insertParameter();
                        break;
                    }

                    char x = q.Dequeue();

                    if (x == '\'')
                    {
                        insertParameter();

                        // add until we find last '
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \' 
                            if (x == '\\' && q.Count > 0 && q.Peek() == '\'')
                            {
                                currentParameter.Append('\'');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '\'')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else if (x == '"')
                    {
                        insertParameter();

                        // add until we find last "
                        while (true)
                        {
                            x = q.Dequeue();

                            // if next 2 characetrs are \"
                            if (x == '\\' && q.Count > 0 && q.Peek() == '"')
                            {
                                currentParameter.Append('"');
                                q.Dequeue();
                                continue;
                            }

                            if (x == '"')
                            {
                                insertParameter();
                                break;
                            }

                            currentParameter.Append(x);
                        }
                    }
                    else
                    {
                        currentParameter.Append(x);
                    }
                }
            }
            catch
            {
                if (Debugger.IsAttached) { Debugger.Break(); }
                throw new Exception("Invalid curl command");
            }

            StringBuilder finalCommand = new StringBuilder();

            foreach (var p in parameters)
            {
                if (p.StartsWith("-"))
                {
                    finalCommand.Append(p);
                    finalCommand.Append(" ");
                    continue;
                }

                var temp = p;

                if (temp.Contains("\""))
                {
                    temp = temp.Replace("\"", "\\\"");
                }
                if (temp.Contains("'"))
                {
                    temp = temp.Replace("'", "\\'");
                }

                finalCommand.Append($"\"{temp}\"");
                finalCommand.Append(" ");
            }


            using (var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "curl.exe",
                    Arguments = finalCommand.ToString(),
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true,
                    WorkingDirectory = Environment.SystemDirectory
                }
            })
            {
                proc.Start();

                proc.WaitForExit(timeoutInSeconds*1000);

                return proc.StandardOutput.ReadToEnd();
            }
        }
    }

代码有点长的原因是,如果执行单引号,则Windows会给您一个错误。换句话说,该命令curl 'https://google.com'将在Linux上运行,而在Windows上将不运行。由于我创建了该方法,因此您可以使用单引号并完全像在Linux上运行curl命令一样运行curl命令。此代码还会检查转义字符,例如\'\"

例如,将此代码用作

var output = ExecuteCurl(@"curl 'https://google.com' -H 'Accept: application/json, text/javascript, */*; q=0.01'");

如果您在哪里再次运行相同的字符串C:\Windows\System32\curl.exe,它将无法正常工作,因为某些原因,Windows不喜欢单引号。


2

我知道这是一个非常老的问题,但是我发布了此解决方案以防万一。我最近遇到了这个问题,谷歌带领我来到这里。此处的答案有助于我理解问题,但是由于我的参数组合,仍然存在问题。最终解决我问题的是curl到C#转换器。它是一个非常强大的工具,并支持Curl的大多数参数。它生成的代码几乎可以立即运行。


2
我会非常小心,不要在上面粘贴任何敏感数据(例如auth cookie)...
Adi H

0

从控制台应用程序调用cURL不是一个好主意。

但是您可以使用TinyRestClient,它使构建请求更加容易:

var client = new TinyRestClient(new HttpClient(),"https://api.repustate.com/");

client.PostRequest("v2/demokey/score.json").
AddQueryParameter("text", "").
ExecuteAsync<MyResponse>();

0

好吧,如果您不熟悉C#和cmd-line exp。您可以使用“ https://curl.olsh.me/ ”之类的在线网站,也可以搜索curl到C#转换器将返回可以为您完成此操作的网站。

或者,如果您使用的是邮递员,则可以使用“生成代码段”,而邮递员代码生成器的唯一问题是对RestSharp库的依赖。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.