C# http post请求帮助类
using System; using System.Collections.Specialized; using System.IO; using System.Net; using System.Reflection; using System.Text; namespace CommonSD { public class HttpPostHelper { public static string Post(string url, string postData) { return Post(url, postData, "application/x-www-form-urlencoded"); } public static string Post(string url, string postData, string contentType) { HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); request.ContentType = contentType; request.Method = "POST"; request.Timeout = 300000; byte[] bytes = Encoding.UTF8.GetBytes(postData); request.ContentLength = bytes.Length; Stream writer = request.GetRequestStream(); writer.Write(bytes, 0, bytes.Length); writer.Close(); HttpWebResponse response = (HttpWebResponse) request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8); string result = reader.ReadToEnd(); response.Close(); return result; } public static string Post(string url, string postData, string userName, string password) { HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); request.ContentType = "text/html; charset=UTF-8"; request.Method = "POST"; string usernamePassword = userName + ":" + password; CredentialCache credentialCache = new CredentialCache {{new Uri(url), "Basic", new NetworkCredential(userName, password)}}; request.Credentials = credentialCache; request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword))); byte[] bytes = Encoding.UTF8.GetBytes(postData); request.ContentLength = bytes.Length; Stream writer = request.GetRequestStream(); writer.Write(bytes, 0, bytes.Length); writer.Close(); HttpWebResponse response = (HttpWebResponse) request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.ASCII); string result = reader.ReadToEnd(); response.Close(); return result; } //static CookieContainer cookie = new CookieContainer(); /// <summary> /// /// </summary> /// <param name="url">请求的servlet地址,不带参数</param> /// <param name="postData"></param> /// <returns>请求的参数,key=value&key1=value1</returns> public static string doHttpPost(string url, string postData) { HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); SetHeaderValue(request.Headers, "Content-Type", "application/json"); SetHeaderValue(request.Headers, "Accept", "application/json"); SetHeaderValue(request.Headers, "Accept-Charset", "utf-8"); request.Method = "POST"; request.Timeout = 300000; byte[] bytes = Encoding.UTF8.GetBytes(postData); request.ContentLength = bytes.Length; Stream writer = request.GetRequestStream(); writer.Write(bytes, 0, bytes.Length); writer.Close(); HttpWebResponse response = (HttpWebResponse) request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8); string result = reader.ReadToEnd(); response.Close(); return result; } /// <summary> /// 偶发性超时时试看看 /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <returns></returns> public static string HttpPostForTimeOut(string url, string postData) { //System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); //watch.Start(); GC.Collect(); HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); //int a = Encoding.UTF8.GetByteCount(postData); request.Timeout = 20 * 600 * 1000; ServicePointManager.Expect100Continue = false; ServicePointManager.DefaultConnectionLimit = 200; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8")); //如果JSON有中文则是UTF-8 myStreamWriter.Write(postData); myStreamWriter.Close(); //请求中止,是因为长度不够,还没写完就关闭了. HttpWebResponse response = (HttpWebResponse) request.GetResponse(); //watch.Stop(); //停止监视 //TimeSpan timespan = watch.Elapsed; //获取当前实例测量得出的总时间 //System.Diagnostics.Debug.WriteLine("打开窗口代码执行时间:{0}(毫秒)", timespan.TotalMinutes); //总毫秒数 Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream ?? throw new InvalidOperationException(), Encoding.GetEncoding("utf-8")); string registerResult = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return registerResult; } public static void SetHeaderValue(WebHeaderCollection header, string name, string value) { var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic); if (property != null) { if (property.GetValue(header, null) is NameValueCollection collection) collection[name] = value; } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)