Shubham Avasthi
Shubham Avasthi

Reputation: 192

How to perform the following curl request in C#?

I am exhausted after searching a lot, but still have no idea.

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"

Upvotes: 0

Views: 563

Answers (2)

Stuart
Stuart

Reputation: 5496

Here you go:

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

This uses HttpClient and needs to be inside of an async method.

Although HttpClient implements IDisposable, it is considered best practice to reuse the instance and not dispose of it.

If you are using .NET 4.0 and lower then you can use the older 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();

Upvotes: 2

Darjan Bogdan
Darjan Bogdan

Reputation: 3900

If you are working in .Net 4.5 +, you can use HttpClient and async methods as well:

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
    }
}

Upvotes: 1

Related Questions