1.1.4 利用HttpClient调用 WebApi
对于一个.net客户端程序,它可以利用HttpClient来进行Web Api的调用。由于WebA Api的调用本质上就是一次普通的发送请求与接收响应的过程,
所有HttpClient其实可以作为一般意义上发送HTTP请求的工具。
在ConsoleApp代表的控制台应用中,我们利用HttpClient来调用以Self Host方式寄宿的Web Api。
为该项目引用Common, System.Net.Http
class Program { static void Main(string[] args) { Process(); Console.Read(); } private async static void Process() { //获取当前联系人列表 HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); IEnumerable<Contact> contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); Console.WriteLine("当前联系人列表:"); ListContacts(contacts); //添加新的联系人 Contact contact = new Contact { Name = "王五", PhoneNo = "17712348765", EmailAddress = "wangwuEmali@123.com", Address = "天津" }; await httpClient.PostAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts", contact); Console.WriteLine("添加联系人:王五"); response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); ListContacts(contacts); //修改现有的某个联系人 response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts/001"); contact = (await response.Content.ReadAsAsync<IEnumerable<Contact>>()).First(); contact.Name = "修改过的张三"; await httpClient.PutAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts", contact); Console.WriteLine("修改联系人001的信息"); response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); ListContacts(contacts); //删除现有的某个联系人 response = await httpClient.DeleteAsync("http://localhost/selfhost/api/contacts/002"); Console.WriteLine("删除联系人“002”"); response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts"); contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>(); ListContacts(contacts); } private static void ListContacts(IEnumerable<Contact> contacts) { foreach (Contact item in contacts) { Console.WriteLine("{0,-6}{1,-6}{2,-20}{3,-10}", item.ID, item.Name, item.EmailAddress, item.Address); Console.WriteLine(); } } }
效果如下