如何在C#中执行以下curl请求?

时间:2017-01-16 22:35:24

标签: c# visual-studio curl request

经过大量搜索后我筋疲力尽,但仍然不知道。

curl -X GET --header "Accept: application/json" --header "app_id: yyyyyyyy" --header "app_key: xxxxxxxxxxxxxxxxxxxxxxxxxxx" "https://od-api.oxforddictionaries.com:443/api/v1/inflections/en/changed"

2 个答案:

答案 0 :(得分:1)

你走了:

var client = new HttpClient();
client.BaseAddress = new Uri("https://od-api.oxforddictionaries.com:443/api/v1");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("app_id", "yyyyyyyy");
client.DefaultRequestHeaders.Add("app_key", "xxxxxxxxxxxxxxxxxxxxxxxxxxx");
var response = await client.GetAsync("/inflections/en/changed");

这使用HttpClient,需要在async方法内。

虽然HttpClient实现了IDisposable,但最好的做法是重用该实例而不是将其丢弃。

如果您使用的是.NET 4.0及更低版本,则可以使用较早的HttpWebRequest apis:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://od-api.oxforddictionaries.com:443/api/v1/inflections/en/changed");

request.Accept = "application/json";
request.Headers.Add("app_id", "yyyyyyyy");
request.Headers.Add("app_key", "xxxxxxxxxxxxxxxxxxxxxxxxxxx");

var response = (HttpWebResponse)request.GetResponse();

答案 1 :(得分:0)

如果您使用的是.Net 4.5 +,您也可以使用HttpClient和异步方法:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("app_id", @"yyyyyyyy");
    client.DefaultRequestHeaders.Add("app_key", @"xxxxxxxxxxxxxxxxxxxxxxxxxxx");

    var response = await client.GetAsync("https://od-api.oxforddictionaries.com:443/api/v1/inflections/en/changed");
    if (response.IsSuccessStatusCode)
    {
        //Do your thing
    }
}