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

  • 相关阅读:
    【转】一个URL编码和解码的C++类
    ofstream的问题
    如何解决"应用程序无法启动,因为应用程序的并行配置不正确"问题(转载)
    最小生成树 prim & kruskal
    【2018百度之星资格赛】F 三原色图
    cout 按进制数出
    【2018百度之星资格赛】 A 问卷调查
    银河英雄传说
    读入读出挂!!
    关押罪犯
  • 原文地址:https://www.cnblogs.com/runliuv/p/15134008.html
Copyright © 2011-2022 走看看