user519670
user519670

Reputation: 685

Submitting a POST with headers and parameters

I need to connect to an API but all the examples they give to connect are using CURL. I need to implement it in C#. I have narrowed it down to needing to use the httpclient class, but i cant seem to find any examples or tutorials that explain exactly what i need. Here is the CURL query they say to use. Can anyone point me in the right direction of how to convert it into c#?

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXX' -d '{ "grant_type": "password", "client_id": XXXXX, "username": "[email protected]", "password": "XXXXXXXXXXXXX|XXXXXXXXXXXXX" }' 'https://XXXXXXXXXXXX/XXXXXXXX/XXXXX/XXXXXX/authorize'

Thanks in advance :)

Upvotes: 0

Views: 209

Answers (1)

Basem Sayej
Basem Sayej

Reputation: 3403

You can use the HttpClient class as following

 using (var client = new HttpClient())
            {

                client.BaseAddress = new Uri("http://yourdomain.com");
                client.DefaultRequestHeaders.Accept.Clear();

                //this line is optional in case you are using basic authentication
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                                                        "Basic",
                                                        Convert.ToBase64String(
                                                            System.Text.ASCIIEncoding.ASCII.GetBytes(
                                                               string.Format("{0}:{1}", "username", "password"))));

                var content = new FormUrlEncodedContent(new[] 
                            {
                                new KeyValuePair<string, string>("", "login")
                            });
                HttpResponseMessage response = client.PostAsync("http//yourdomain.com", content).Result;
                if (response.IsSuccessStatusCode)
                {
                    var _result = response.Content.ContentToString();

                }
            }

Upvotes: -1

Related Questions