HttpWebRequest,HttpWebResponse 使用
1 | 目的:工作中已经两次使用了,特此记录一下,并写好注释 |
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | /// <summary> /// HttpWebRequest的基本配置 /// </summary> public class HttpConfig { /// <summary> /// 协议:http/https /// </summary> public string protocol { set ; get ; } /// <summary> /// 发送端发送的数据格式 /// </summary> public string contentType { set ; get ; } /// <summary> /// 客户端希望接受的数据类型 /// </summary> public string accept { set ; get ; } /// <summary> /// 标识请求者的一些信息,如浏览器类型和版本、操作系统,使用语言等信息(IE,Firefox以“Mozilla/....”开头) /// </summary> public string userAgent { set ; get ; } /// <summary> /// 超时时间 /// </summary> public int timeOut { set ; get ; } /// <summary> /// 请求body的编码类型:utf-8/gbk2312/gbk /// </summary> public string encoding { set ; get ; } /// <summary> /// 请求方式:GET/POST /// </summary> public string method { set ; get ; } /// <summary> /// 是否保持持续连接。默认为true /// </summary> public bool keepAlive { set ; get ; } /// <summary> /// cookie集合 /// </summary> public CookieContainer cc = null ; /// <summary> /// http header集合 /// </summary> public WebHeaderCollection whc = null ; public HttpConfig() { protocol = "http" ; contentType = "application/xml;charset=utf-8" ; accept = "application/xml" ; userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)" ; timeOut = 15; encoding = "utf-8" ; method = "POST" ; keepAlive = false ; } public HttpConfig(Dictionary< string , string > dctCookieKeyValus, string Domain, Dictionary< string , string > dctHeaderKeyValus) : this () { GetCookieContainer(dctCookieKeyValus, Domain); GetWebHeaderCollection(dctHeaderKeyValus); } /// <summary> /// 设置cookies /// </summary> /// <param name="dctKeyValus"></param> /// <param name="Domain"></param> public void GetCookieContainer(Dictionary< string , string > dctKeyValus, string Domain) { if (dctKeyValus.Count > 0) { cc = new CookieContainer(); foreach ( string key in dctKeyValus.Keys) { Cookie cookie = new Cookie(key, dctKeyValus[key]); cookie.Domain = "" ; cc.Add(cookie); } } } /// <summary> /// 设置httpheaders /// </summary> /// <param name="dctKeyValus"></param> public void GetWebHeaderCollection(Dictionary< string , string > dctKeyValus) { if (dctKeyValus.Count > 0) { whc = new WebHeaderCollection(); foreach ( string key in dctKeyValus.Keys) { whc.Add( string .Format( "{0}:{1}" , key, dctKeyValus[key])); } } } } public class HttpRequestAndResponse { HttpConfig httpConfig = null ; public HttpRequestAndResponse(HttpConfig httpconfig) { httpConfig = httpconfig; } /// <summary> /// 调过https验证 /// </summary> private static bool CheckValidationResult( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true ; } public string RequestAndResponse( string url, string requestXML, ref string errString) { string response = "" ; HttpWebRequest req = null ; HttpWebResponse res = null ; try { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); /*最大并接数*************************************************************/ ServicePointManager.DefaultConnectionLimit = 200; //最大并发连接数 //如果写在配置文件里 app.config // <system.net> // <connectionManagement> // <!--表示把对任何域名的请求最大http连接数都设置为200--> // <add address = "*" maxconnection = "200" /> // </connectionManagement> //</system.net> req = WebRequest.Create(url) as HttpWebRequest; /*HttpWebRequest的基本属性设置*************************************************************/ req.ProtocolVersion = HttpVersion.Version10; req.UserAgent = httpConfig.userAgent; req.KeepAlive = httpConfig.keepAlive; req.Timeout = 1000 * httpConfig.timeOut; req.Method = httpConfig.method; req.Accept = httpConfig.accept; req.ContentType = httpConfig.contentType; /*写入http头部信息*************************************************************************/ if (httpConfig.whc != null ) req.Headers = httpConfig.whc; /*cookie拼接*************************************************************/ if (httpConfig.cc != null ) req.CookieContainer = httpConfig.cc; /*写入requestXML***************************************************************************/ if (! string .IsNullOrEmpty(requestXML)) { byte [] bytes = System.Text.Encoding.GetEncoding(httpConfig.encoding).GetBytes(requestXML); if (bytes.Length > 0) { req.ContentLength = bytes.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(bytes, 0, bytes.Length); reqStream.Close(); } } } /*HttpWebResponse获取服务器数据**************************************************************/ res = req.GetResponse() as HttpWebResponse; using (Stream resStream = res.GetResponseStream()) { using (StreamReader resStreamReader = new StreamReader(resStream, Encoding.GetEncoding(httpConfig.encoding))) { response = resStreamReader.ReadToEnd(); } } } catch (WebException e) { HttpWebResponse exceptionRes = e.Response as HttpWebResponse; errString = "#Status-line\n" ; string format = "protocolVersion:{0}\tstatusCode:{1}\tstatusDescription:{2}\n" ; errString += string .Format(format, exceptionRes.ProtocolVersion, Convert.ToInt32(exceptionRes.StatusCode), exceptionRes.StatusDescription); errString += "#Header\n" ; format = "num[{0}]:({1}:{2})\n" ; for ( int i = 0; i < exceptionRes.Headers.Count; i++) { errString += string .Format(format, i, exceptionRes.Headers.Keys[i], exceptionRes.Headers[i]); } errString += "#Body\n" ; using (Stream resStream = exceptionRes.GetResponseStream()) { using (StreamReader resStreamReader = new StreamReader(resStream, Encoding.GetEncoding(httpConfig.encoding))) { errString += resStreamReader.ReadToEnd() + "\n" ; resStreamReader.Close(); resStream.Close(); } } errString += "#end\n" ; exceptionRes.Close(); } catch (Exception e) { errString = e.ToString(); } finally { if (res!= null ) { res.Close(); res = null ; } if (req != null ) { req.Abort(); req = null ; } } return response; } } |
分类:
c#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本