0

This is repeated question but I could not get solution. Please tell me how to call web API from C#. Here I am using github data.

 string URL = "https://api.github.com/users";

 string DATA = @"{ ""login"":""mojombo""
                 }";
 string strStatus = CallService(URL, DATA);

 public string CallService(string URL, string DATA)
        {
            string strStatus = string.Empty;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            client.BaseAddress = new System.Uri(URL);
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic");
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            System.Net.Http.HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");
            HttpResponseMessage messge = client.PostAsync(URL, content).Result;
            if (messge.IsSuccessStatusCode)
            {
                string result = messge.Content.ReadAsStringAsync().Result;
                strStatus = result;
            }

            return strStatus;
        }
Rao
  • 71
  • 1
  • 9

0 Answers0