码迷,mamicode.com
首页 > Windows程序 > 详细

c# HttpWebRequest 模拟HTTP post 传递JSON参数

时间:2017-08-15 19:49:44      阅读:576      评论:0      收藏:0      [点我收藏+]

标签:position   res   adt   c#   ons   传递   coding   end   string   

 //HTTP post   JSON 参数
        private string HttpPost(string Url, Object ticket)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(ticket.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, ticket);
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            string param = Encoding.UTF8.GetString(dataBytes);
                byte[] bs = Encoding.ASCII.GetBytes(param);
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = bs.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }
                HttpWebResponse hwr = req.GetResponse() as HttpWebResponse;
                System.IO.StreamReader myreader = new System.IO.StreamReader(hwr.GetResponseStream(), Encoding.UTF8);
                string responseText = myreader.ReadToEnd();
            return responseText;
        }

 

 

导入对应的dll  ,  Object参数可以随意,实体类传什么,json参数就是什么。

c# HttpWebRequest 模拟HTTP post 传递JSON参数

标签:position   res   adt   c#   ons   传递   coding   end   string   

原文地址:http://www.cnblogs.com/j2ee-web-01/p/7366927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!