/// <summary> /// 为请求准备参数 /// </summary> ///<param name="objhttpItem">参数列表</param> /// <param name="_Encoding">读取数据时的编码方式</param> private void SetRequest(HttpItem objhttpItem) { // 验证证书 SetCer(objhttpItem); //设置Header参数 if (objhttpItem.Header != null) { try { request.Headers = objhttpItem.Header; } catch { return; } } // 设置代理 SetProxy(objhttpItem); //请求方式Get或者Post request.Method = objhttpItem.Method; request.Timeout = objhttpItem.Timeout; request.ReadWriteTimeout = objhttpItem.ReadWriteTimeout; //Accept request.Accept = objhttpItem.Accept; //ContentType返回类型 request.ContentType = objhttpItem.ContentType; //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息 request.UserAgent = objhttpItem.UserAgent; // 编码 SetEncoding(objhttpItem); //设置Cookie SetCookie(objhttpItem); //来源地址 request.Referer = objhttpItem.Referer; //是否执行跳转功能 request.AllowAutoRedirect = objhttpItem.Allowautoredirect; //设置Post数据 SetPostData(objhttpItem); //设置最大连接 if (objhttpItem.Connectionlimit > 0) { request.ServicePoint.ConnectionLimit = objhttpItem.Connectionlimit; } }
///<summary> ///采用https协议访问网络,根据传入的URl地址,得到响应的数据字符串。 ///</summary> ///<param name="objhttpItem">参数列表</param> ///<returns>String类型的数据</returns> public HttpResult GetHtml(HttpItem objhttpItem) { //准备参数 SetRequest(objhttpItem); //调用专门读取数据的类 return GetHttpRequestData(objhttpItem); }
/// <summary> /// 设置Post数据 /// </summary> /// <param name="objhttpItem">Http参数</param> private void SetPostData(HttpItem objhttpItem) { //验证在得到结果时是否有传入数据 if (request.Method.Trim().ToLower().Contains("post")) { //写入Byte类型 if (objhttpItem.PostDataType == PostDataType.Byte) { //验证在得到结果时是否有传入数据 if (objhttpItem.PostdataByte != null && objhttpItem.PostdataByte.Length > 0) { request.ContentLength = objhttpItem.PostdataByte.Length; request.GetRequestStream().Write(objhttpItem.PostdataByte, 0, objhttpItem.PostdataByte.Length); } }//写入文件 else if (objhttpItem.PostDataType == PostDataType.FilePath) { StreamReader r = new StreamReader(objhttpItem.Postdata, encoding); byte[] buffer = Encoding.Default.GetBytes(r.ReadToEnd()); r.Close(); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } else { //验证在得到结果时是否有传入数据 if (!string.IsNullOrEmpty(objhttpItem.Postdata)) { byte[] buffer = Encoding.Default.GetBytes(objhttpItem.Postdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } } } }
/// <summary> /// 设置代理 /// </summary> /// <param name="objhttpItem">参数对象</param> private void SetProxy(HttpItem objhttpItem) { if (string.IsNullOrEmpty(objhttpItem.ProxyUserName) && string.IsNullOrEmpty(objhttpItem.ProxyPwd) && string.IsNullOrEmpty(objhttpItem.ProxyIp)) { //不需要设置 } else { //设置代理服务器 WebProxy myProxy = new WebProxy(objhttpItem.ProxyIp, false); //建议连接 myProxy.Credentials = new NetworkCredential(objhttpItem.ProxyUserName, objhttpItem.ProxyPwd); //给当前请求对象 request.Proxy = myProxy; //设置安全凭证 request.Credentials = CredentialCache.DefaultNetworkCredentials; } }
/// <summary> /// 设置编码 /// </summary> /// <param name="objhttpItem">Http参数</param> private void SetEncoding(HttpItem objhttpItem) { if (string.IsNullOrEmpty(objhttpItem.Encoding) || objhttpItem.Encoding.ToLower().Trim() == "null") { //读取数据时的编码方式 encoding = null; } else { //读取数据时的编码方式 encoding = System.Text.Encoding.GetEncoding(objhttpItem.Encoding); } }
/// <summary> /// 设置Cookie /// </summary> /// <param name="objhttpItem">Http参数</param> private void SetCookie(HttpItem objhttpItem) { //获取当前的cookie if (!string.IsNullOrEmpty(objhttpItem.Cookie)) { //Cookie request.Headers[HttpRequestHeader.Cookie] = objhttpItem.Cookie; } //设置Cookie if (objhttpItem.CookieCollection != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(objhttpItem.CookieCollection); } if (objhttpItem.Cc != null) { request.CookieContainer = objhttpItem.Cc; } //request.CookieContainer = cc; //chkCookie(cc, objhttpItem); }
/// <summary> /// 设置证书 /// </summary> /// <param name="objhttpItem"></param> private void SetCer(HttpItem objhttpItem) { if (!string.IsNullOrEmpty(objhttpItem.CerPath)) { //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); //初始化对像,并设置请求的URL地址 request = (HttpWebRequest)WebRequest.Create(GetUrl(objhttpItem.URL)); //创建证书文件 X509Certificate objx509 = new X509Certificate(objhttpItem.CerPath); //添加到请求里 request.ClientCertificates.Add(objx509); } else { //初始化对像,并设置请求的URL地址 try { request = (HttpWebRequest)WebRequest.Create(GetUrl(objhttpItem.URL)); } catch { return; } } }
/// <summary> /// 根据相传入的数据,得到相应页面数据 /// </summary> /// <param name="strPostdata">传入的数据Post方式,get方式传NUll或者空字符串都可以</param> /// <returns>string类型的响应数据</returns> private HttpResult GetHttpRequestData(HttpItem objhttpitem) { //返回参数 HttpResult result = new HttpResult(); try { #region 得到请求的response result.CookieCollection = new CookieCollection(); response = (HttpWebResponse)request.GetResponse(); result.Header = response.Headers; if (response.Cookies != null) { result.CookieCollection = response.Cookies; } if (response.Headers["set-cookie"] != null) { result.Cookie = response.Headers["set-cookie"]; } MemoryStream _stream = new MemoryStream(); //GZIIP处理 if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase)) { //开始读取流并设置编码方式 //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240); //.net4.0以下写法 _stream = GetMemoryStream(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)); } else { //开始读取流并设置编码方式 //response.GetResponseStream().CopyTo(_stream, 10240); //.net4.0以下写法 _stream = GetMemoryStream(response.GetResponseStream()); } //获取Byte byte[] RawResponse = _stream.ToArray(); //是否返回Byte类型数据 if (objhttpitem.ResultType == ResultType.Byte) { result.ResultByte = RawResponse; return result; } //无视编码 if (encoding == null) { string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length); //<meta(.*?)charset([\s]?)=[^>](.*?)> //<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline); string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty; charter = charter.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(";", string.Empty); if (charter.Length > 0) { charter = charter.ToLower().Replace("iso-8859-1", "gbk").Split(' ')[0]; encoding = Encoding.GetEncoding(charter); } else { if (response.CharacterSet != null) { if (response.CharacterSet.ToLower().Trim() == "iso-8859-1") { encoding = Encoding.GetEncoding("gbk"); } else { if (string.IsNullOrEmpty(response.CharacterSet.Trim())) { encoding = Encoding.UTF8; } else { encoding = Encoding.GetEncoding(response.CharacterSet); } } } } } //得到返回的HTML try { result.Html = encoding.GetString(RawResponse); _stream.Close(); response.Close(); } catch { return null; } //最后释放流 #endregion } catch (WebException ex) { //这里是在发生异常时返回的错误信息 result.Html = "String Error"; response = (HttpWebResponse)ex.Response; return result; } if (objhttpitem.IsToLower) { result.Html = result.Html;//.ToLower(); } return result; }
private void chkCookie(CookieContainer cc, HttpItem objhttpItem) { if (cc.Count > 0) { cool = cc.GetCookies(new Uri(objhttpItem.URL))[0].Value; if (objhttpItem.CookieCollection != null) { oldcool = objhttpItem.CookieCollection[0].Value; } else if (newcool.Contains(oldcool) && oldcool.Length > 0 && newcool.Length > 0) { // throw new WebException("cookie是用户传来的上一次内容", WebExceptionStatus.UnknownError); System.Windows.Forms.MessageBox.Show("cookie是用户传来的上一次内容"); return; //throw new Exception("cookie是用户传来的上一次内容"); } else if (newcool.Contains(cool) && cool.Length > 0 && newcool.Length > 0) { System.Windows.Forms.MessageBox.Show("本次请求的cookie与上次相同"); return; //throw new WebException("本次请求的cookie与上次相同"); } else { oldcool = cool; newcool = oldcool; } } }