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参数就是什么。

转载于:https://www.cnblogs.com/j2ee-web-01/p/7366927.html

你可能感兴趣的:(c# HttpWebRequest 模拟HTTP post 传递JSON参数)