这是一个重复的问题,但我无法得到解决方案。请告诉我如何从C#调用Web API。我在这里使用github数据。
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;
}