ASP.NET HTTP模拟提交通用类 GET POST
用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | WebRequestSugar ws = new WebRequestSugar(); //可选参数 //ws.SetAccept //ws.SetContentType //ws.SetCookie //ws.SetTimeOut //ws.SetIsAllowAutoRedirect //GET var html= ws.HttpGet( "http://localhost:24587/Http/HttpTest.aspx" ); //带参GET var paras= new Dictionary< string , string >() ; paras.Add( "name" , "skx" ); paras.Add( "id" , "100" ); var html2 = ws.HttpGet( "http://localhost:24587/Http/HttpTest.aspx" ,paras ); //POST var postHtml= ws.HttpPost( "http://localhost:24587/Http/HttpTest.aspx" , paras); //post and file var postHtml2 = ws.HttpUploadFile( "http://localhost:24587/Http/HttpTest.aspx" , "文件地址可以是数组" , paras); |
类:
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 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.IO; using System.Text.RegularExpressions; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using System.Collections.Specialized; namespace SyntacticSugar { /// <summary> /// ** 描述:模拟HTTP POST GET请求并获取数据 /// ** 创始时间:2015-11-24 /// ** 修改时间:- /// ** 作者:sunkaixuan /// ** 使用说明: /// </summary> public class WebRequestSugar { /// <summary> /// 设置cookie /// </summary> private CookieContainer cookie; /// <summary> /// 是否允许重定向 /// </summary> private bool allowAutoRedirect = true ; /// <summary> /// contentType /// </summary> private string contentType = "application/x-www-form-urlencoded" ; /// <summary> /// accept /// </summary> private string accept = "*/*" ; /// <summary> /// 过期时间 /// </summary> private int time = 5000; /// <summary> /// 设置请求过期时间(单位:毫秒)(默认:5000) /// </summary> /// <param name="time"></param> public void SetTimeOut( int time) { this .time = time; } /// <summary> /// 设置accept(默认:*/*) /// </summary> /// <param name="accept"></param> public void SetAccept( string accept) { this .accept = accept; } /// <summary> /// 设置contentType(默认:application/x-www-form-urlencoded) /// </summary> /// <param name="contentType"></param> public void SetContentType( string contentType) { this .contentType = contentType; } /// <summary> /// 设置Cookie /// </summary> /// <param name="cookie"></param> public void SetCookie(CookieContainer cookie) { this .cookie = cookie; } /// <summary> /// 是否允许重定向(默认:true) /// </summary> /// <param name="allowAutoRedirect"></param> public void SetIsAllowAutoRedirect( bool allowAutoRedirect) { this .allowAutoRedirect = allowAutoRedirect; } /// <summary> /// post请求返回html /// </summary> /// <param name="url"></param> /// <param name="postDataStr"></param> /// <returns></returns> public string HttpPost( string url, Dictionary< string , string > postdata) { string postDataStr = null ; if (postdata != null && postdata.Count > 0) { postDataStr = string .Join( "&" , postdata.Select(it => it.Key + "=" + it.Value)); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.AllowAutoRedirect = allowAutoRedirect; request.Method = "POST" ; request.Accept = accept; request.ContentType = this .contentType; request.Timeout = time; request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); if (cookie != null ) request.CookieContainer = cookie; //cookie信息由CookieContainer自行维护 Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding( "gb2312" )); myStreamWriter.Write(postDataStr); myStreamWriter.Close(); HttpWebResponse response = null ; try { this .SetCertificatePolicy(); response = (HttpWebResponse)request.GetResponse(); } catch (System.Exception ex) { throw ex; } //获取重定向地址 //string url1 = response.Headers["Location"]; if (response != null ) { Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding( "utf-8" )); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } else { return null ; //post请求返回为空 } } /// <summary> /// get请求获取返回的html /// </summary> /// <param name="url">无参URL</param> /// <param name="querydata">参数</param> /// <returns></returns> public string HttpGet( string url, Dictionary< string , string > querydata) { if (querydata != null && querydata.Count > 0) { url += "?" + string .Join( "&" , querydata.Select(it => it.Key + "=" + it.Value)); } return HttpGet(url); } /// <summary> /// get请求获取返回的html /// </summary> /// <param name="url"></param> /// <returns></returns> public string HttpGet( string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET" ; request.ContentType = "text/html;charset=UTF-8" ; request.CookieContainer = cookie; request.Accept = this .accept; request.Timeout = time; this .SetCertificatePolicy(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // response.Cookies = cookie.GetCookies(response.ResponseUri); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding( "utf-8" )); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } /// <summary> /// POST文件 /// </summary> /// <param name="url"></param> /// <param name="file">文件路径</param> /// <param name="postdata"></param> /// <returns></returns> public string HttpUploadFile( string url, string file, Dictionary< string , string > postdata) { return HttpUploadFile(url, file, postdata, Encoding.UTF8); } /// <summary> /// POST文件 /// </summary> /// <param name="url"></param> /// <param name="file">文件路径</param> /// <param name="postdata">参数</param> /// <param name="encoding"></param> /// <returns></returns> public string HttpUploadFile( string url, string file, Dictionary< string , string > postdata, Encoding encoding) { return HttpUploadFile(url, new string [] { file }, postdata, encoding); } /// <summary> /// POST文件 /// </summary> /// <param name="url"></param> /// <param name="files">文件路径</param> /// <param name="postdata">参数</param> /// <returns></returns> public string HttpUploadFile( string url, string [] files, Dictionary< string , string > postdata) { return HttpUploadFile(url, files, postdata, Encoding.UTF8); } /// <summary> /// POST文件 /// </summary> /// <param name="url"></param> /// <param name="files">文件路径</param> /// <param name="postdata">参数</param> /// <param name="encoding"></param> /// <returns></returns> public string HttpUploadFile( string url, string [] files, Dictionary< string , string > postdata, Encoding encoding) { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString( "x" ); byte [] boundarybytes = Encoding.ASCII.GetBytes( "\r\n--" + boundary + "\r\n" ); byte [] endbytes = Encoding.ASCII.GetBytes( "\r\n--" + boundary + "--\r\n" ); //1.HttpWebRequest HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST" ; request.KeepAlive = true ; request.Accept = this .accept; request.Timeout = this .time; request.AllowAutoRedirect = this .allowAutoRedirect; if (cookie != null ) request.CookieContainer = cookie; request.Credentials = CredentialCache.DefaultCredentials; using (Stream stream = request.GetRequestStream()) { //1.1 key/value string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}" ; if (postdata != null ) { foreach ( string key in postdata.Keys) { stream.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string .Format(formdataTemplate, key, postdata[key]); byte [] formitembytes = encoding.GetBytes(formitem); stream.Write(formitembytes, 0, formitembytes.Length); } } //1.2 file string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n" ; byte [] buffer = new byte [4096]; int bytesRead = 0; for ( int i = 0; i < files.Length; i++) { stream.Write(boundarybytes, 0, boundarybytes.Length); string header = string .Format(headerTemplate, "file" + i, Path.GetFileName(files[i])); byte [] headerbytes = encoding.GetBytes(header); stream.Write(headerbytes, 0, headerbytes.Length); using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read)) { while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, bytesRead); } } } //1.3 form end stream.Write(endbytes, 0, endbytes.Length); } //2.WebResponse HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader stream = new StreamReader(response.GetResponseStream())) { return stream.ReadToEnd(); } } /// <summary> /// 获得响应中的图像 /// </summary> /// <param name="url"></param> /// <returns></returns> public Stream GetResponseImage( string url) { Stream resst = null ; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.KeepAlive = true ; req.Method = "GET" ; req.AllowAutoRedirect = allowAutoRedirect; req.CookieContainer = cookie; req.ContentType = this .contentType; req.Accept = this .accept; req.Timeout = time; Encoding myEncoding = Encoding.GetEncoding( "UTF-8" ); this .SetCertificatePolicy(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); resst = res.GetResponseStream(); return resst; } catch { return null ; } } /// <summary> /// 正则获取匹配的第一个值 /// </summary> /// <param name="html"></param> /// <param name="pattern"></param> /// <returns></returns> private string GetStringByRegex( string html, string pattern) { Regex re = new Regex(pattern, RegexOptions.IgnoreCase); MatchCollection matchs = re.Matches(html); if (matchs.Count > 0) { return matchs[0].Groups[1].Value; } else return "" ; } /// <summary> /// 正则验证返回的response是否正确 /// </summary> /// <param name="html"></param> /// <param name="pattern"></param> /// <returns></returns> private bool VerifyResponseHtml( string html, string pattern) { Regex re = new Regex(pattern); return re.IsMatch(html); } //注册证书验证回调事件,在请求之前注册 private void SetCertificatePolicy() { ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate; } /// <summary> /// 远程证书验证,固定返回true /// </summary> private static bool RemoteCertificateValidate( object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { return true ; } } } |
分类:
C#语法糖
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?