使用HttpClient操作ASP.NET Web API 2.1增删改查

使用NuGet包安装Microsoft ASP.NET Web API 2.1 Client Libraries,

调用方式代码如下:

 1        HttpClient client = new HttpClient();
 2             client.BaseAddress = new Uri("http://localhost:2471/");//基地址
 3             client.DefaultRequestHeaders.Accept.Add(
 4                 new MediaTypeWithQualityHeaderValue("application/json"));
 5             HttpResponseMessage response = client.GetAsync("api/values").Result;
 6             if (response.IsSuccessStatusCode)
 7             {
 8                 var products = response.Content.ReadAsAsync<IEnumerable<ProductInfo>>().Result;
 9             }
10             else
11             {
12                 Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
13             }
14 
15           
16             
17             //HTTP Post请求
18             ProductInfo pro = new ProductInfo();
19             pro.dateTime1 = DateTime.Now;
20             pro.Int = 1;
21              response = client.PutAsJsonAsync<ProductInfo>("api/Values", pro).Result;
22             if (response.IsSuccessStatusCode)
23             {
24                 
25             }
26             else
27             {
28                 Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
29             }
30 
31            response =  client.DeleteAsync("api/values/5").Result;
32            if (response.IsSuccessStatusCode)
33            {
34 
35            }
36            else
37            {
38                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
39            }

values控制器代码如下:

 1 public IEnumerable<ProductInfo> GetList()
 2         {
 3             //string s = this.Request.Headers.GetValues("YXLCookie").FirstOrDefault();
 4 
 5             ProductInfo p = new ProductInfo();
 6             p.Int = 432;
 7             p.string1 = "432432";
 8             p.dateTime2 = DateTime.Now;
 9 
10 
11             ProductItem pi = new ProductItem() { Int = 1, string1 = "432432" };
12             p.productItem = pi;
13 
14             ProductInfo p2 = new ProductInfo();
15             p2.Int = 432;
16             p2.string1 = "432432";
17             p2.dateTime2 = DateTime.Now;
18 
19 
20             ProductItem pi2 = new ProductItem() { Int = 1, string1 = "432432", dateTime1 = DateTime.Now };
21             p2.productItem = pi2;
22 
23             List<ProductInfo> list = new List<ProductInfo>();
24             list.Add(p);
25             list.Add(p2);
26 
27             return list;
28         }
29 
30       
31 
32         // POST api/values
33         public void PostProduct([FromBody]ProductInfo pro)
34         {
35 
36         }
37         // DELETE api/values/5
38         public void Delete(int id)
39         {
40         }


使用JsonConvert要安装Json.NET,使用NuGet安装Json.NET如果我们新增json格式的数据,需要将json格式转换为object对象,代码如下:

 1 HttpClient client = httpClient;
 2             client.BaseAddress = new Uri("https://api.weixin.qq.com");
 3             client.DefaultRequestHeaders.Accept.Add(
 4                 new MediaTypeWithQualityHeaderValue("application/json"));
 5             
 6            
 7             object s1 = JsonConvert.DeserializeObject<object>(@"{
 8                  'button':[
 9                  {    
10                       'type':'click',
11                       'name':'协运跟踪',
12                       'key':'V1001_TODAY_MUSIC'
13                   },
14                   {
15                        'type':'click',
16                        'name':'金牌航线',
17                        'key':'V1001_TODAY_SINGER'
18                   },
19                   {
20                        'name':'菜单测试',
21                        'sub_button':[
22                        {    
23                            'type':'view',
24                            'name':'运价',
25                            'url':'http://weixin.51xieyun.com/price/index'
26                         },
27                         {
28                            'type':'view',
29                            'name':'首页',
30                            'url':'http://weixin.51xieyun.com'
31                         },
32                         {
33                            'type':'click',
34                            'name':'赞一下我们',
35                            'key':'V1001_GOOD'
36                         }]
37                    }]
38              }
39             ");
40             HttpResponseMessage response = client.PostAsJsonAsync<object>("cgi-bin/menu/create?access_token=dPm9S5I6bMKp3QHhcxxqyJhuaNH4h20lJaIeNi-gXVbkpQCsUdyvOLbfQCPmDFWMIS0LowOXSVfu1iD47VC9nolu29-rRJ0oWUhIX0WRDYKPOIZtf4onsSvFePdt1iX9jba5rmhR769OG7cye--V4g", s1).Result;
41             if (response.IsSuccessStatusCode)
42             {
43                 var products = response.Content.ReadAsAsync<object>().Result;
44             }
45             else
46             {
47                 Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
48             }

 

posted @ 2014-02-14 16:23  学亮  阅读(1059)  评论(0编辑  收藏  举报