在C#中进行cURL调用

smo*_*med 77 .net c# curl http

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

curl -d "text=This is a block of text" \
    http://api.repustate.com/v2/demokey/score.json
Run Code Online (Sandbox Code Playgroud)

我试着像这里发布的问题那样做,但我无法正确填写属性.

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

http://api.repustate.com/v2/demokey/score.json?text="This%20is%20a%20block%20of%20text"
Run Code Online (Sandbox Code Playgroud)

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

cas*_*One 136

好吧,你不会直接调用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());
}
Run Code Online (Sandbox Code Playgroud)

另请注意,HttpClient该类对处理不同的响应类型有更好的支持,并且比前面提到的选项更好地支持异步操作(以及取消它们).

  • 我已经尝试过关注类似问题的代码,但是我遇到了等待只能设置为异步方法的错误? (5认同)
  • @Jay大多数这些方法都会返回“Task&lt;T&gt;”,您可以不使用“async”,然后正常处理返回类型(您必须调用“Task&lt;T&gt;.Result”。注意,您'不过,最好使用“async”,因为您会浪费线程等待结果。 (2认同)
  • 这可以用于拨打这样的电话吗?`curl -k -i -H "Accept: application/json" -H "X-Application: &lt;AppKey&gt;" -X POST -d 'username=&lt;username&gt;&amp;password=&lt;password&gt;' https://identitysso.betfair .com/api/登录` (2认同)

onl*_*mas 15

或者在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);
Run Code Online (Sandbox Code Playgroud)

  • 基本用法示例不能开箱即用。RestSharp 就是垃圾。 (3认同)

Ben*_*enW 10

下面是一个工作示例代码.

请注意,您需要添加对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();
Run Code Online (Sandbox Code Playgroud)

参考:TheDeveloperBlog.com


Bob*_*Bob 6

我知道这是一个非常古老的问题,但我发布这个解决方案以防它对某人有帮助。我最近遇到了这个问题,谷歌引导我来到这里。这里的答案可以帮助我理解问题,但由于我的参数组合仍然存在问题。最终解决我的问题的是curl to C# converter。它是一个非常强大的工具,支持Curl的大部分参数。它生成的代码几乎可以立即运行。

  • 我会非常小心,不要在那里粘贴任何敏感数据(如身份验证cookie)...... (9认同)

Ton*_*Nam 5

迟到的回应,但这就是我最终做的。如果您想像在 linux 上运行它们一样运行 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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

代码有点长的原因是因为如果你执行单引号,windows 会给你一个错误。换句话说,该命令curl 'https://google.com'将在 linux 上运行,而在 windows 上不起作用。多亏了我创建的这种方法,您可以使用单引号并完全按照在 linux 上运行的方式运行 curl 命令。此代码还检查转义字符,例如\'\"

例如使用此代码作为

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

如果您再次运行相同的字符串C:\Windows\System32\curl.exe,它将不起作用,因为出于某种原因,Windows 不喜欢单引号。