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

Posted 越过那个限制

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# HttpWebRequest 模拟HTTP post 传递JSON参数相关的知识,希望对你有一定的参考价值。

 //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参数的主要内容,如果未能解决你的问题,请参考以下文章

C#模拟HTTP请求Post JSON

C#,HttpWebRequest模拟发送Post请求

c# httpwebrequest 模拟登陆

C#后台HttpWebRequest模拟跨域Ajax请求,注册Windows服务到服务器上

C#后台HttpWebRequest模拟跨域Ajax请求,注册Windows服务到服务器上

C# HttpWebRequest - 如何确定是不是发生了 HTTP 301?