zoukankan      html  css  js  c++  java
  • HttpClient异步请求Post传递Json

    HttpClient异步Post请求,HttpClient.PostAsync(String, HttpContent, CancellationToken),String为Post的Url,HttpContent为发送到服务器的 HTTP 请求内容,就是Post过去的数据了。

    HttpContent,常用的有FormUrlEncodedContent、StringContent。

    FormUrlEncodedContent是以KeyValuePair形式出现的,假如你要传递的内容以KeyValue形式出现,可用。但一般应用中我们都是将实体转成Json后传递的,谁还有哪个功夫一个个KeyValue对的写啊。因此StringContent就是我经常使用的方法。

            public async void aa()
            {
                JavaScriptSerializer jss = new JavaScriptSerializer();
    
                string json = jss.Serialize(entity);
                string postUrl = "http://xxxx";
                var content = new StringContent(json);
    
                var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
                //创建HttpClient(注意传入HttpClientHandler)
                using (var http = new HttpClient(handler))
                {
    
                    var response = await http.PostAsync(postUrl, content); //await异步等待回应
                    //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
                    string result = (await response.Content.ReadAsStringAsync());//result就是返回的结果。
                }
            }

     服务端:在Action中:

                var stream = HttpContext.Current.Request.InputStream;
                byte[] byts = new byte[stream.Length];
                stream.Read(byts, 0, (int)stream.Length);
                
                string postjson = Encoding.UTF8.GetString(byts);
                return postjson;//以UTF8形式获取数据

     

  • 相关阅读:
    SpringCloud大白话之服务注册中心
    Spring事物白话文
    spring的IOC过程剖析
    2、Spring-RootApplicationContext-refresh
    1、spring与springmvc父子容器
    mysql 5.7 主从设置
    centos7下安装oracle11gR2
    lepus安装报错处理
    centos 6.9安装nginx1.4
    Linux 面试题 合集
  • 原文地址:https://www.cnblogs.com/luhuanong/p/4586228.html
Copyright © 2011-2022 走看看