码迷,mamicode.com
首页 > Windows程序 > 详细

ASP.NET Web Api 实践系列(二)Get/Post方式调用Web Api

时间:2015-08-11 13:48:29      阅读:444      评论:0      收藏:0      [点我收藏+]

标签:

    本文给出Get/Post方式访问Web Api的帮助方法,对于Put/Delete方式的调用跟Post调用类似。

    一、Web Api调用帮助类

    下面给出Web Api调用帮助类的代码:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Net.Http;
  4 using System.Net.Http.Headers;
  5 using System.Text;
  6 using System.Web;
  7 
  8 namespace TestApi
  9 {
 10     /// <summary>
 11     /// WebApi访问帮助类
 12     /// </summary>
 13     public class WebApiHepler
 14     {
 15         /// <summary>
 16         /// 生成最终URL
 17         /// </summary>
 18         /// <param name="baseUrl">基准URL(不含查询串)</param>
 19         /// <param name="dictParam">查询参数字典</param>
 20         /// <returns>最终URL</returns>
 21         private static string GetLastUrl(string baseUrl, Dictionary<string, string> dictParam)
 22         {
 23             var sbUrl = new StringBuilder(baseUrl);
 24             if (dictParam != null && dictParam.Count > 0)
 25             {
 26                 sbUrl.Append("?");
 27                 int index = 0;
 28                 foreach (var item in dictParam)
 29                 {
 30                     sbUrl.Append(string.Format("{0}={1}", item.Key,
 31                         HttpUtility.UrlEncode(item.Value, Encoding.UTF8)));
 32                     if (index < dictParam.Count - 1)
 33                     {
 34                         sbUrl.Append("&");
 35                     }
 36                     index++;
 37                 }
 38             }
 39             var url = sbUrl.ToString();
 40             return url;
 41         }
 42 
 43         /// <summary>
 44         /// GET方式调用Web Api
 45         /// </summary>
 46         /// <param name="baseUrl">基准URL(不含查询串)</param>
 47         /// <param name="dictParam">查询参数字典</param>
 48         /// <param name="result">返回数据(Json格式)</param>
 49         /// <param name="errMsg">出错信息</param>
 50         /// <returns>成功与否</returns>
 51         public static bool Get(string baseUrl, Dictionary<string, string> dictParam, out string result, out string errMsg)
 52         {
 53             errMsg = string.Empty;
 54             result = string.Empty;
 55             try
 56             {
 57                 using (var client = new HttpClient())
 58                 {
 59                     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 60                     var url = GetLastUrl(baseUrl, dictParam);
 61                     var tmpResult = client.GetAsync(url).Result;
 62                     tmpResult.EnsureSuccessStatusCode();
 63                     result = tmpResult.Content.ReadAsStringAsync().Result;
 64                     return true;
 65                 }
 66             }
 67             catch (Exception ex)
 68             {
 69                 errMsg = ex.Message;
 70                 return false;
 71             }
 72             
 73         }
 74 
 75         /// <summary>
 76         /// POST方式调用Web Api
 77         /// </summary>
 78         /// <param name="baseUrl">基准URL(不含查询串)</param>
 79         /// <param name="dictParam">查询参数字典</param>
 80         /// <param name="parseData">传递实体数据(Json格式)</param>
 81         /// <param name="result">返回数据(Json格式)</param>
 82         /// <param name="errMsg">出错信息</param>
 83         /// <returns>成功与否</returns>
 84         public static bool Post(string baseUrl, Dictionary<string, string> dictParam, string parseData, out string result, out string errMsg)
 85         {
 86             errMsg = string.Empty;
 87             result = string.Empty;
 88             try
 89             {
 90                 using (var client = new HttpClient())
 91                 {
 92                     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 93                     var url = GetLastUrl(baseUrl, dictParam);
 94                     var content = new StringContent(parseData, Encoding.UTF8);
 95                     content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
 96                     var tmpResult = client.PostAsync(url, content).Result;
 97                     tmpResult.EnsureSuccessStatusCode();
 98                     result = tmpResult.Content.ReadAsStringAsync().Result;
 99                     return true;
100                 }
101             }
102             catch (Exception ex)
103             {
104                 errMsg = ex.Message;
105                 return false;
106             }
107         }
108     }
109 }

    二、部分说明

    对以上的代码作部分说明:

  • GetLastUrl方法用于根据基准URL和查询参数字典获取最终URL
  • client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));这句代码表示希望服务返回Json字符串。
  • content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 表示以Json格式传递实体内容。

 

ASP.NET Web Api 实践系列(二)Get/Post方式调用Web Api

标签:

原文地址:http://www.cnblogs.com/huatao/p/4720595.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!