mvc 4 api 的调用有很多种,最常见也最简单的一种是 用 ajax 的方式在前端界面中调用, 如果是在后台代码中调用 ,是要复杂一些,以下是 以 post 的方式调用 api 的封装好的方法:
/// <summary> /// api 调用公共方法 /// </summary> /// <param name="url"> api url </param> /// <param name="param"> 参数 </param> /// <returns></returns> public static HttpResponseMessage PostApi(string url, Dictionary<string, string> param) { var dict = new Dictionary<string, string>(); dict.Add("", Newtonsoft.Json.JsonConvert.SerializeObject(param)); var content = new FormUrlEncodedContent(dict); var httpClient = new HttpClient(); return httpClient.PostAsync(url, content).Result; }
string url = "apiurl"; // api url var dict = new Dictionary<string, string>(); dict.Add("name", "wisdomhu"); dict.Add("age", "7"); HttpResponseMessage response = PostApi(url, dict); Console.WriteLine("{0}", response.StatusCode);