zoukankan      html  css  js  c++  java
  • 使用HttpWebRequest向webapi传递数据并接收

    1.通过路由接收参数,一般直接通过Url拼接直接匹配路由对应参数

    这个直接通过设置路由,然后Url的位置对应即可;

    2.通过QueryString传递参数

    一般常见于Get访问数据传参;

    3.通过[FromBody]直接在形参接收数据

    客户端代码:

    private async void Btn_SendData_Click(object sender, EventArgs e)
            {
                if (string.IsNullOrEmpty(TB_SendDataUrl.Text))
                    return;
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(TB_SendDataUrl.Text);
                //request.ContentType = "application/x-www-form-urlencoded";//post发送数据必须使用这个标头才能被webapi [frombody]接收
                request.ContentType = "application/json";   //如果用了newtonsoft json 转换数据,那么必须用此标头,否则服务器将无法解析数据
                request.Method = "post";
    
                //发送的数据
                List<Person> listP = new List<Person>();
                Person p1 = new Person { ID = 1, Name = "张三", Age = 27 };
                Person p2 = new Person { ID = 2, Name = "李四", Age = 25 };
                Person p3 = new Person { ID = 3, Name = "王五", Age = 28 };
                listP.Add(p1); listP.Add(p2); listP.Add(p3);
    
    
                byte[] byteArray;
                Person p = new Person { ID = 1, Name = "张三", Age = 27 };
                //byteArray = Encoding.UTF8.GetBytes(ParseToString(p));
                string data = await JsonConvert.SerializeObjectAsync(listP);//直接序列化比上一行代码 更方便
                byteArray = Encoding.UTF8.GetBytes(data);//对数据进行转码,可以将中文数据进行传输
                request.ContentLength = byteArray.Length;
    
                Stream reqStream = await request.GetRequestStreamAsync();
                reqStream.Write(byteArray,0,byteArray.Length);
                reqStream.Close();
    
                string responseFromServer = string.Empty;
                WebResponse response = await request.GetResponseAsync();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseFromServer = reader.ReadToEnd();
                }
                if(string.IsNullOrEmpty(responseFromServer))
                {
                    TB_SendResponseData.Text = "NULL";
                }
                else
                {
                    TB_SendResponseData.Text = responseFromServer;
                    List<Person> resData = JsonConvert.DeserializeObject<List<Person>>(responseFromServer);
                    
                }
                response.Close();
            }

    这里注意如果使用Newtonsoft将传输数据转换成了json,需要将contenttype设置为"application/json",这里十分关键,如果不是这个表头,服务端将不能正确解析数据

    服务端代码:

       [HttpPost]
            public List<Person> SendListData([FromBody] List<Person> listP)
            {
    
                return listP;
            }

    4.通过 解析Request.Content  中的请求消息实体得到数据,这种一般是通过Post上传的数据

     [HttpPost]
            public async Task<List<Person>> SendListJsontData()
            {
                List<Person> data = await this.Request.Content.ReadAsAsync<List<Person>>();
                return data;
            }

    由于Task是4.5以上框架引入的,也可以在4.5以下框架中写成非异步调用的方式:

    [HttpPost]
            public string PostNewData()
            {
                var t = this.Request.Content.ReadAsStringAsync();
                string data = t.Result;
                return data;
            }

    前台使用的代码(推荐):

    public static string HttpPost(string url, string PostData)
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                //这里只有使用var data = HttpContext.Current.Request.Form["Name"].ToString();才切换到表单
                //如果api使用Request.Content.ReadAsStringAsync();则无所谓切换
                request.ContentType = "application/x-www-form-urlencoded ";//根据服务端进行 切换
                //request.ContentType = "application/json; charset=utf-8 ";
    
                byte[] buffer = encoding.GetBytes(PostData);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }

    主函数调用

    static void Main(string[] args)
            {
           
    string url = "http://localhost:50041/api/Home/PostNewData"; //string data = "Name="; //for (int i = 0; i < 1000; i++) //{ // data += Guid.NewGuid().ToString() + ";"; //} string data = "Id=9527&Name=zhangSan&Category=A8&Price=88"; string res = HttpPost(url, data); Console.WriteLine($"结果:{res}"); Console.ReadKey(); }

    使用.Net内置的方法即可读到传输数据。

  • 相关阅读:
    环形链表II 找环入口
    最短无序连续子数组 复制数组排序后与原数组相比
    和为K的子数组 暴力 或 hash+前缀
    在排序数组中查找元素的第一个和最后一个位置 二分法+递归
    NodeJs 批量重命名文件,并保存到指定目录
    NodeJs 批量图片瘦身,重设尺寸和图片质量并保存到指定目录
    NodeJs 获取照片拍摄日期和视频拍摄日期,并按日期目录存档
    Oracle迁移记录
    Oracle数据库迁移前的准备工作(创建用户并且分配权限及表空间)
    Oracle 11g R2性能优化 10046 event【转载】
  • 原文地址:https://www.cnblogs.com/LeeSki/p/12410523.html
Copyright © 2011-2022 走看看