標籤:
本文給出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