zoukankan      html  css  js  c++  java
  • C#.NET 使用HttpWebRequest发送JSON

    方法:

    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

  • 相关阅读:
    怎么把分页按钮(首页,尾页等)放在表格右下角处?(已解决)
    zabbix单位符号
    容器、可迭代对象、迭代器、生成器之间的关系.
    Zabbix housekeeper processes more than 75% busy
    zabbix 告警信息模板
    zabbix 历史数据和趋势数据
    socket沾包问题
    面向对象--进阶
    面向对象
    列表 元组 字典
  • 原文地址:https://www.cnblogs.com/runliuv/p/15134008.html
Copyright © 2011-2022 走看看