runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  710 随笔 :: 0 文章 :: 127 评论 :: 98万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

方法:

 

复制代码
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

posted on   runliuv  阅读(3309)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2017-08-12 ubuntu 16.04 安装VS CODE时 此软件来自第三方且可能包含非自由组件
点击右上角即可分享
微信分享提示