ck168

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

目前所了解的请求WebAPI的方式有通过后台访问api 和通过js 直接访问api接口

首先介绍下通过后台访问api的方法,可以使用HttpClient的方式也可以使用WebRequest的方式

1、HttpClient的方式

  (1)Get请求

        string url = "http://10.1.1.1:8080/";
        public ActionResult GetAll()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(url);

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.GetAsync("api/goods/getlist?pageindex=0&pagesize=10").Result;  // Blocking call(阻塞调用)! 

            var result = "";

            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;

                JavaScriptSerializer Serializer = new JavaScriptSerializer();
                var items = Serializer.DeserializeObject(result);
                return Json(items);
            }
            else
            {
                return Json(result);
            }

        } 
View Code

  (2)Post请求

        [HttpPost]
        public ActionResult AddGood(string paramObj)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(url);

            JavaScriptSerializer jss = new JavaScriptSerializer();
            var item = jss.Deserialize<Good>(paramObj);

            var content = new FormUrlEncodedContent(new Dictionary<string, string>()       
                {    
                    {"Id","382accff-57b2-4d6e-ae84-a61e00a3e3b5"},
                    {"Category","111"}
                 });

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.PostAsync("api/goods/add", content).Result;


            var result = "";
            if (response.IsSuccessStatusCode)
            {
                result = response.Content.ReadAsStringAsync().Result;

                JavaScriptSerializer Serializer = new JavaScriptSerializer();
                var items = Serializer.DeserializeObject(result);
                return Json(items);
            }
            return View();
        }    
View Code

2、WebRequest的方式(该方式是post请求的时候传入json字符串转换成流的形式,无需再将json转换成需要的实体对象了)

所以这种方式只需写一个公共的方法,每次调用的时候传入地址和参数即可

公共方法如下:

    public class WebRequestHelper
    {
        public static string GetRequest(string url)
        {
            string responseStr = string.Empty;

            WebRequest request = WebRequest.Create(url);
            request.Method = "Get";
            var response = request.GetResponse();
            Stream ReceiveStream = response.GetResponseStream();
            using (StreamReader stream = new StreamReader(ReceiveStream, Encoding.UTF8))
            {
                responseStr = stream.ReadToEnd();
            }

            return responseStr;
        }


        public static string PostRequest(string url, string postParameter)
        {
            string responseStr = string.Empty;

            WebRequest request = WebRequest.Create(url);
            request.Method = "Post";
            request.ContentType = "application/json";

            byte[] requestData = System.Text.Encoding.UTF8.GetBytes(postParameter);
            request.ContentLength = requestData.Length;

            Stream newStream = request.GetRequestStream();
            newStream.Write(requestData, 0, requestData.Length);
            newStream.Close();

            var response = request.GetResponse();
            Stream ReceiveStream = response.GetResponseStream();
            using (StreamReader stream = new StreamReader(ReceiveStream, Encoding.UTF8))
            {
                responseStr = stream.ReadToEnd();
            }

            return responseStr;
        }

        /// <summary>
        /// Http的 WebRequest的特定实现
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="JSONData"></param>
        /// <returns></returns>
        public static string GetResponseData(string Url, string JSONData)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "application/json";
            Stream reqstream = request.GetRequestStream();
            reqstream.Write(bytes, 0, bytes.Length);

            //声明一个HttpWebRequest请求  
            request.Timeout = 90000;
            //设置连接超时时间  
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.UTF8;

            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string strResult = streamReader.ReadToEnd();
            streamReceive.Dispose();
            streamReader.Dispose();

            return strResult;
        }
    }
View Code

调用的使用方法

  (1)Get请求

        public ActionResult GetAll()
        {
            string result = WebRequestHelper.GetRequest(url + "api/goods/getlist?pageindex=0&pagesize=10");
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            var items = Serializer.DeserializeObject(result);
            return Json(items);
        }
View Code

  (2)Post请求

        [HttpPost]
        public ActionResult AddGood(string paramObj)
        {
            string result = WebRequestHelper.PostRequest(url + "api/goods/add", paramObj);
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            var items = Serializer.DeserializeObject(result);
            return Json(items);
        }
View Code

页面通过jquery调用

代码如下:

        $.ajax({
            type: "get",
            url: "/goods/getall",
            dataType: "json",
            data: null,
            //data: JSON.stringify({
            //    id: "382accff-57b2-4d6e-ae84-a61e00a3e3b6"
            //}),
            contentType: "application/json;charset-utf-8",
            success: function (data) {
                console.log(data);
            }
        });

        var paramObj = { Id: "382accff-57b2-4d6e-ae84-a61e00a3e3b8",Category:111};

        $.ajax({
            type: "post",
            url: "/goods/AddGood",
            dataType: "json",
            //data: null,
            data: JSON.stringify({
                paramObj: JSON.stringify(paramObj)
            }),
            contentType: "application/json;charset-utf-8",
            success: function (data) {
                console.log(data);
            }
        });
View Code

 

posted on 2016-07-08 11:22  HelloWorld168  阅读(16166)  评论(0编辑  收藏  举报