接口Get和Post.从服务端到客户端的实现

1.客户端核心代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {

            //获得Get方法接口
            WebRequest request;
            WebResponse response;
            System.IO.Stream st;
            string resStr;
            System.Web.Script.Serialization.JavaScriptSerializer jsoner;
            ResultPig rpig;
            List<ResultPig> list;
            TestGet(out request, out response, out st, out resStr, out jsoner, out rpig, out list);

            //获得Get方法接口
            WebGet("http://localhost:4393/api/values");

            //获得Post方法接口
            WebPost("http://localhost:4393/api/values","","aa");
            

            return View();
        }


        /// <summary>
        /// GET,获取url的返回值
        /// </summary>
        /// <param name="url">eg:http://m.weather.com.cn/atad/101010100.html </param>
        public string WebGet(string url)
        {
            try
            {
                string strBuff = "";
                Uri httpURL = new Uri(url);
                ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换 
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
                ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换 
                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
                ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容 
                ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理 
                Stream respStream = httpResp.GetResponseStream();
                ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以 
                //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8) 
                StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);//Encoding.UTF8
                strBuff = respStreamReader.ReadToEnd();
                return strBuff;
            }
            catch
            {

                return "400";
            }
        }


        /// <summary>
        /// Post方法
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="method">方法action</param>
        /// <param name="param">json参数</param>
        /// <returns></returns>
        public static string WebPost(string url, string method, string param)
        {
            //转换输入参数的编码类型,获取bytep[]数组 
            byte[] byteArray = Encoding.UTF8.GetBytes("json=" + param);
            //初始化新的webRequst
            //1. 创建httpWebRequest对象
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url + "/" + method));
            //2. 初始化HttpWebRequest对象
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            //3. 附加要POST给服务器的数据到HttpWebRequest对象(附加POST数据的过程比较特殊,它并没有提供一个属性给用户存取,需要写入HttpWebRequest对象提供的一个stream里面。)
            Stream newStream = webRequest.GetRequestStream();//创建一个Stream,赋值是写入HttpWebRequest对象提供的一个stream里面
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();
            //4. 读取服务器的返回信息
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string phpend = php.ReadToEnd();
            return phpend;

        }

        private static void TestGet(out WebRequest request, out WebResponse response, out System.IO.Stream st, out string resStr, out System.Web.Script.Serialization.JavaScriptSerializer jsoner, out ResultPig rpig, out List<ResultPig> list)
        {
            //1.0请求的webapi的url:http://localhost:4393/api/values
            //1.0构造一个制定url请求对象
            request = WebRequest.Create("http://localhost:4393/api/values");
            //2.0指定请求的方法为get
            request.Method = "Get";


            //3.0发出请求获取相应对象
            response = request.GetResponse();

            //4.0获取相应报文体中的数据
            st = response.GetResponseStream();

            //5.0将st转换成字符串
            resStr = string.Empty;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(st))
            {
                //从当前流的开始位置读至结束位置
                resStr = sr.ReadToEnd();//{"Age":1,"Name":"大黄狗"}
            }

            //6.0将结果绑定到Grid上
            //    将json格式的字符串反序列化成集合
            jsoner = new System.Web.Script.Serialization.JavaScriptSerializer();
            rpig = jsoner.Deserialize<ResultPig>(resStr);
            如果结果是[{},{}]
            //jsoner.Deserialize<List<ResultPig>>(resStr);

            list = new List<ResultPig>() { rpig };
        }
    
        
        public class ResultPig
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
    }
}
2.服务端核心代码:

配置修改为JSON格式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace MVCWebApi2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //移除XML格式,返回值自动就变成json格式
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            // Web API 配置和服务


            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
            // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
            // 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。
            //config.EnableQuerySupport();

            // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
            // 有关详细信息,请参阅: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
    }
}
 

接口返回值:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MVCWebApi2.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public HttpResponseMessage Get()
        {
            string json = "{\"Age\":85,\"Name\":\"不知道\"}";
            return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public HttpResponseMessage Post([FromBody]string value)
        {
            string json = "{\"Age\":85,\"Name\":\"不知道\"}";
            return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

 

案例资源下载:https://download.csdn.net/download/weixin_42401291/10721863

 

程序开发(ASP.NET、C#)、网站建设(H5)、小程序、公众号等相关开发联系QQ:1174787689 备注 程序开发合作

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧方

开发程序不易

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值