如何在C#中进行cURL调用

时间:2017-01-10 11:01:48

标签: c# .net curl

如何通过C#console app进行以下cURL调用。

curl -k https://serverName/clearprofile.ashx -H "Host: example.com"

我试过CurlSharp。遗憾的是,由于缺少 libcurlshim64 程序集,我无法成功构建此项目。

here我明白最好的方法是使用HttpClient类,但我不知道如何从我的控制台应用程序进行上述cURL调用。

1 个答案:

答案 0 :(得分:0)

如果你只是想要一些简单的东西,我会使用.Net Framework中内置的HttpClient类,如下所示:

using System.Net.Http;
using System.Threading.Tasks;

namespace ScrapCSConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Host = "example.com";
            Task<string> task = client.GetStringAsync("https://serverName/clearprofile.ashx");
            task.Wait();
            Console.WriteLine(task.Result);
        }
    }
}

对于更复杂的东西,你也可以像这样使用HttpWebRequest类:

using System;
using System.IO;
using System.Net;

namespace ScrapCSConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://google.co.uk");

            request.Host = "example.com";

            HttpStatusCode code;
            string responseBody = String.Empty;

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    code = response.StatusCode;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException webEx)
            {
                using (HttpWebResponse response = (HttpWebResponse)webEx.Response)
                {
                    code = response.StatusCode;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseBody = reader.ReadToEnd();
                    }
                }
            }

            Console.WriteLine($"Status: {code}");
            Console.WriteLine(responseBody);
        }
    }
}