Consuming API with C# code using HttpClient

“HttpClient” is a class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

Here is a C# code snippet for consuming a POST api method. A custom function “apiPost” which expected a JSON string parameter for POST api.

public async Task<CServiceStatus> apiPost(string data)
        {
           
            var token = "[REQUIRED_TOKEN]"; //If Authorization Required
            string BaseAddress = "[YOUR_API_ENDPOINT]";
            
            CServiceStatus cServiceStatus = new CServiceStatus(); //Custom Class for holding response
            using (var client = new HttpClient())
            {
                try
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    client.BaseAddress = new Uri(BaseAddress);

                    client.DefaultRequestHeaders.Authorization
                             = new AuthenticationHeaderValue("Basic", token); //If Authorization Required

                    var httpContent = new StringContent(data, Encoding.UTF8, "application/json");

                    var responseTask = client.PostAsync("", httpContent);
                    responseTask.Wait();

                    var result = responseTask.Result;
                    cServiceStatus.RequestStatus = result.StatusCode;
                    cServiceStatus.ReturnMessage = result.RequestMessage.ToString();
                    if (result.IsSuccessStatusCode)
                    {
                        var result_data = await result.Content.ReadAsStringAsync();
                        cServiceStatus.ReturnJson = JsonConvert.DeserializeObject(result_data).ToString();                       
                    }                    
                }
                catch (Exception ex)
                {
                    cServiceStatus.RequestStatus = HttpStatusCode.ServiceUnavailable;
                    cServiceStatus.ReturnMessage = ex.Message;
                }
                
            }
            return cServiceStatus;
        }

Here i have created a class “CServiceStatus” for holding the response data.

public class CServiceStatus
    {
        private HttpStatusCode requestStatus = HttpStatusCode.NotFound;
        private string returnJson = string.Empty;
        private string returnMessage = string.Empty;
        public HttpStatusCode RequestStatus
        {
            get { return requestStatus; }
            set { requestStatus = value; }
        }
        public string ReturnJson
        {
            get { return returnJson; }
            set { returnJson = value; }
        }
        public string ReturnMessage
        {
            get { return returnMessage; }
            set { returnMessage = value; }
        }

    }

How to use?

String str="{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}";
apiPost(str);

Leave a Comment