简体   繁体   中英

Consuming REST API from curl call

How do you consume REST API given just a cUrl call?

I am using Clickatell's REST API. I would like to use C# and HttpClient as it is the latest and greatest way to make REST calls. I am trying to "convert" the call to be used in HttpClient. I've managed to do some of it but not sure how to do the rest.

cUrl:

curl -i \
-X GET \
-H "X-Version: 1" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer Your Authorization Token" \
-H "Accept: application/json" \
-s \
https://api.clickatell.com/rest/account/balance

This is what I currently have:

using (HttpClient httpClient = new HttpClient())
{
     httpClient.BaseAddress = new Uri("https://api.clickatell.com/rest/account/balance");
     httpClient.DefaultRequestHeaders.Accept.Clear();
     httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "my_cliackatell_token");
     httpClient.DefaultRequestHeaders.Add("X-Version", "1");
}

I'm not sure what the following means and how do I implement them into the above code:

-i \
-H "Accept: application/json" \
-s \

How do I complete the above mentioned when doing the POST?

Are these 2 settings the same thing? -H "Content-Type: application/json" and -H "Accept: application/json"

you can consume a get method call as follows(This is just an example)

HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:56851/");

        // Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("api/User").Result;

        if (response.IsSuccessStatusCode)
        {
           // do logic
        }
        else
        {
            MessageBox.Show("Error Code" + 
            response.StatusCode + " : Message - " + response.ReasonPhrase);
        }

Refer the below link to learn more about Httpclient

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM