• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#.NET使用HttpWebRequest发送JSON

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

方法:

 

public static string HttpPostJson(string url, string postStr, int timeOut, string charset)
        {
            HttpWebRequest wreq = null;
            HttpWebResponse res = null;
            string strRst = "";

            #region http web request

            Encoding ecd = Encoding.GetEncoding(charset);

            byte[] data = ecd.GetBytes(postStr);
            wreq = (HttpWebRequest)WebRequest.Create(url);
            wreq.Timeout = timeOut * 1000;
            wreq.ReadWriteTimeout = timeOut * 1000;
            wreq.Method = "POST";
            wreq.KeepAlive = false;
            wreq.ContentType = "application/json;charset=utf-8";
            wreq.ServicePoint.Expect100Continue = false; //当服务器恢复正常时,访问已经是200时,这个线程还是返回操作超时

            wreq.ContentLength = data.Length;
            using (Stream putStream = wreq.GetRequestStream())
            {
                putStream.Write(data, 0, data.Length);
            }

            res = wreq.GetResponse() as HttpWebResponse;
            byte[] by = new byte[800];
            using (Stream stream = res.GetResponseStream())
            {
                int size = 1024;
                int read = 0;
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] buffer = new byte[size];
                    do
                    {
                        read = stream.Read(buffer, 0, size);
                        ms.Write(buffer, 0, read);
                    } while (read > 0);

                    by = ms.ToArray();
                }
            }

            strRst = ecd.GetString(by);

            if (res != null)
                res.Close();
            if (wreq != null)
                wreq.Abort();//主动释放

            #endregion

            return strRst;
        }

调用:

textBox2.Text = CommonUtils.MU.HttpPostJson(url,textBox1.Text,30,"UTF-8");

END


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
(转)const的内部链接属性(C++中适用)发布时间:2022-07-13
下一篇:
c++文件对齐发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap