C#模拟Http与Https请求框架类实例
本文实例讲述了C#模拟Http与Https请求框架类。分享给大家供大家参考。
具体实现方法如下:
usingSystem.Text; usingSystem.Net; usingSystem.IO; usingSystem.Text.RegularExpressions; usingSystem.Security.Cryptography.X509Certificates; usingSystem.Net.Security;
namespaceWebRequestTest { ///<summary> ///动态类,每个实例使用单独session ///</summary> publicclassHttpHelperNew { publicCookieContainercookie=newCookieContainer(); ///<summary> ///post请求返回html ///</summary> ///<paramname="Url"></param> ///<paramname="postDataStr"></param> ///<returns></returns> publicstringHttpPost(stringUrl,stringpostDataStr) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(Url); //request.AllowAutoRedirect=false;//禁止自动重定向 request.Method="POST"; request.ContentType="application/x-www-form-urlencoded"; request.ContentLength=Encoding.UTF8.GetByteCount(postDataStr); request.CookieContainer=cookie;//cookie信息由CookieContainer自行维护 StreammyRequestStream=request.GetRequestStream(); StreamWritermyStreamWriter=newStreamWriter(myRequestStream,Encoding.GetEncoding("gb2312")); myStreamWriter.Write(postDataStr); myStreamWriter.Close();
HttpWebResponseresponse=null; try { this.SetCertificatePolicy(); response=(HttpWebResponse)request.GetResponse(); } catch(System.Exceptionex) { } //获取重定向地址 //stringurl1=response.Headers["Location"]; if(response!=null) { StreammyResponseStream=response.GetResponseStream(); StreamReadermyStreamReader=newStreamReader(myResponseStream,Encoding.GetEncoding("utf-8")); stringretString=myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); returnretString; } else { return"error";//post请求返回为空 } }
///<summary> ///get请求获取返回的html ///</summary> ///<paramname="Url"></param> ///<paramname="postDataStr"></param> ///<returns></returns> publicstringHttpGet(stringUrl,stringQuerydata) { HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(Url+(Querydata==""?"":"?")+Querydata); request.Method="GET"; request.ContentType="text/html;charset=UTF-8"; request.CookieContainer=cookie; this.SetCertificatePolicy(); HttpWebResponseresponse=(HttpWebResponse)request.GetResponse(); //response.Cookies=cookie.GetCookies(response.ResponseUri); StreammyResponseStream=response.GetResponseStream(); StreamReadermyStreamReader=newStreamReader(myResponseStream,Encoding.GetEncoding("utf-8")); stringretString=myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); returnretString; }
///<summary> ///获得响应中的图像 ///</summary> ///<paramname="url"></param> ///<returns></returns> publicStreamGetResponseImage(stringurl) { Streamresst=null; try { HttpWebRequestreq=(HttpWebRequest)WebRequest.Create(url); req.KeepAlive=true; req.Method="GET"; req.AllowAutoRedirect=true; req.CookieContainer=cookie; req.ContentType="application/x-www-form-urlencoded"; req.Accept="text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; req.Timeout=50000;
EncodingmyEncoding=Encoding.GetEncoding("UTF-8"); this.SetCertificatePolicy(); HttpWebResponseres=(HttpWebResponse)req.GetResponse(); resst=res.GetResponseStream();
returnresst; } catch { returnnull; } }
///<summary> ///正则获取匹配的第一个值 ///</summary> ///<paramname="html"></param> ///<paramname="pattern"></param> ///<returns></returns> publicstringgetStringByRegex(stringhtml,stringpattern) {
Regexre=newRegex(pattern,RegexOptions.IgnoreCase); MatchCollectionmatchs=re.Matches(html); if(matchs.Count>0) { returnmatchs[0].Groups[1].Value; } else return""; }
///<summary> ///正则验证返回的response是否正确 ///</summary> ///<paramname="html"></param> ///<paramname="pattern"></param> ///<returns></returns> publicboolverifyResponseHtml(stringhtml,stringpattern) { Regexre=newRegex(pattern); returnre.IsMatch(html); }
//注册证书验证回调事件,在请求之前注册 privatevoidSetCertificatePolicy() { ServicePointManager.ServerCertificateValidationCallback +=RemoteCertificateValidate; } ///<summary> ///远程证书验证,固定返回true ///</summary> privatestaticboolRemoteCertificateValidate(objectsender,X509Certificatecert, X509Chainchain,SslPolicyErrorserror) { returntrue; } } }