在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
c# HttpWebRequest与HttpWebResponse绝技 阅读原文 如果你想做一些,抓取,或者是自动获取的功能,那么就跟我一起来学习一下Http请求吧。 C# HttpHelper,帮助类,真正的Httprequest请求时无视编码,无视证书,无视Cookie,网页抓取 public static string GetUrltoHtml(string Url,string type) { try { System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); // Get the response instance. System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { return reader.ReadToEnd(); } } catch (System.Exception ex) { //errorMsg = ex.Message; } return ""; } post方法 ///<summary> ///采用https协议访问网络 ///</summary> ///<param name="URL">url地址</param> ///<param name="strPostdata">发送的数据</param> ///<returns></returns> public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using( StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding))) { return reader.ReadToEnd(); } } 这招是入门第一式, 特点: //回调验证证书问题 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // 总是接受 return true; } /// <summary> /// 传入URL返回网页的html代码 /// </summary> /// <param name="Url">URL</param> /// <returns></returns> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 与指定URL创建HTTP请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //创建证书文件 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer"); //添加到请求里 request.ClientCertificates.Add(objx509); // 获取对应HTTP请求的响应 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 获取响应流 Stream responseStream = response.GetResponseStream(); // 对接响应流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 开始读取数据 Char[] sReaderBuffer = new Char[256]; int count = sReader.Read(sReaderBuffer, 0, 256); while (count > 0) { String tempStr = new String(sReaderBuffer, 0, count); content.Append(tempStr); count = sReader.Read(sReaderBuffer, 0, 256); } // 读取结束 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); } post方法 //回调验证证书问题 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { // 总是接受 return true; } ///<summary> ///采用https协议访问网络 ///</summary> ///<param name="URL">url地址</param> ///<param name="strPostdata">发送的数据</param> ///<returns></returns> public string OpenReadWithHttps(string URL, string strPostdata, string strEncoding) { // 这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); //创建证书文件 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer"); //加载Cookie request.CookieContainer = new CookieContainer(); //添加到请求里 request.ClientCertificates.Add(objx509); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding))) { return reader.ReadToEnd(); } }
这招是学会算是进了大门了,凡是需要验证证书才能进入的页面都可以使用这个方法进入,我使用的是证书回调验证的方式,证书验证是否通过在客户端验证,这样的话我们就可以使用自己定义一个方法来验证了,有的人会说那也不清楚是怎么样验证的啊,其它很简单,代码是自己写的为什么要那么难为自己呢,直接返回一个True不就完了,永远都是验证通过,这样就可以无视证书的存在了, 特点: /// <summary> /// 传入URL返回网页的html代码带有证书的方法 /// </summary> /// <param name="Url">URL</param> /// <returns></returns> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { // 与指定URL创建HTTP请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)"; request.Method = "GET"; request.Accept = "*/*"; //如果方法验证网页来源就加上这一句如果不验证那就可以不写了 request.Referer = "http://sufei.cnblogs.com"; CookieContainer objcok = new CookieContainer(); objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值")); objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值")); objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233")); request.CookieContainer = objcok; //不保持连接 request.KeepAlive = true; // 获取对应HTTP请求的响应 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 获取响应流 Stream responseStream = response.GetResponseStream(); // 对接响应流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("gb2312")); // 开始读取数据 Char[] sReaderBuffer = new Char[256]; int count = sReader.Read(sReaderBuffer, 0, 256); while (count > 0) { String tempStr = new String(sReaderBuffer, 0, count); content.Append(tempStr); count = sReader.Read(sReaderBuffer, 0, 256); } // 读取结束 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); } post方法。 ///<summary> ///采用https协议访问网络 ///</summary> ///<param name="URL">url地址</param> ///<param name="strPostdata">发送的数据</param> ///<returns></returns> public string OpenReadWithHttps(string URL, string strPostdata) { Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "post"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentType = "application/x-www-form-urlencoded"; CookieContainer objcok = new CookieContainer(); objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值")); objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("键", "值")); objcok.Add(new Uri("http://sufei.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233")); request.CookieContainer = objcok; byte[] buffer = encoding.GetBytes(strPostdata); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); return reader.ReadToEnd(); } 特点: [code=csharp]response.Cookies[/code]
这就是在你请求后可以得到当次Cookie的方法,直接取得返回给上一个方法使用就行了,上面我们都是自己构造的,在这里直接使用这个Cookie就可以了。 /// <summary> /// 传入URL返回网页的html代码 /// </summary> /// <param name="Url">URL</param> /// <returns></returns> public string GetUrltoHtml(string Url) { StringBuilder content = new StringBuilder(); try { //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); // 与指定URL创建HTTP请求 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); //创建证书文件 X509Certificate objx509 = new X509Certificate(Application.StartupPath + "\\123.cer"); //添加到请求里 request.ClientCertificates.Add(objx509); CookieContainer objcok = new CookieContainer(); objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("键", "值")); objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("键", "值")); objcok.Add(new Uri("http://www.cnblogs.com"), new Cookie("sidi_sessionid", "360A748941D055BEE8C960168C3D4233")); request.CookieContainer = objcok; // 获取对应HTTP请求的响应 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // 获取响应流 Stream responseStream = response.GetResponseStream(); // 对接响应流(以"GBK"字符集) StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 开始读取数据 Char[] sReaderBuffer = new Char[256]; int count = sReader.Read(sReaderBuffer, 0, 256); while (count > 0) { String tempStr = new String(sReaderBuffer, 0, count); content.Append(tempStr); count = sReader.Read(sReaderBuffer, 0, 256); } // 读取结束 sReader.Close(); } catch (Exception) { content = new StringBuilder("Runtime Error"); } return content.ToString(); }
3.如果我们碰到那种需要验证网页来源的方法应该怎么办呢,这种情况其它是有些程序员会想到你可能会使用程序,自动来获取网页信息,为了防止就使用页面来源来验证,就是说只要不是从他们所在页面或是域名过来的请求就不接受,有的是直接验证来源的IP,这些都可以使用下面一句来进入,这主要是这个地址是可以直接伪造的 request.Referer =" http://sufei.cnblogs.com"
呵呵其它很简单因为这个地址可以直接修改。但是如果服务器上验证的是来源的URL那就完了,我们就得去修改数据包了,这个有点难度暂时不讨论。 /// <summary> /// 过滤html标签 /// </summary> /// <param name="strHtml">html的内容</param> /// <returns></returns> public static string StripHTML(string stringToStrip) { // paring using RegEx // stringToStrip = Regex.Replace(stringToStrip, "</p(?:\\s*)>(?:\\s*)<p(?:\\s*)>", "\n\n", RegexOptions.IgnoreCase | RegexOptions.Compiled); stringToStrip = Regex.Replace(stringToStrip, " ", "\n", RegexOptions.IgnoreCase | RegexOptions.Compiled); stringToStrip = Regex.Replace(stringToStrip, "\"", "''", RegexOptions.IgnoreCase | RegexOptions.Compiled); stringToStrip = StripHtmlXmlTags(stringToStrip); return stringToStrip; } private static string StripHtmlXmlTags(string content) { return Regex.Replace(content, "<[^>]+>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled); }
URL转化的方法 #region 转化 URL public static string URLDecode(string text) { return HttpUtility.UrlDecode(text, Encoding.Default); } public static string URLEncode(string text) { return HttpUtility.UrlEncode(text, Encoding.Default); } #endregion
提供一个实际例子,这个是使用IP138来查询手机号码归属地的方法,其它在我的上一次文章里都有,在这里我再放上来是方便大家阅读,这方面的技术其它研究起来很有意思,希望大家多提建议,我相信应该还有更多更好,更完善的方法,在这里给大家提供一个参考吧。感谢支持 /// <summary> /// 输入手机号码得到归属地信息 /// </summary> /// <param name="number">手机号码</param> /// <returns>数组类型0为归属地,1卡类型,2区 号,3邮 编</returns> public static string[] getTelldate(string number) { try { string strSource = GetUrltoHtml("http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + number.Trim()); //归属地 strSource = strSource.Substring(strSource.IndexOf(number)); strSource = StripHTML(strSource); strSource = strSource.Replace("\r", ""); strSource = strSource.Replace("\n", ""); strSource = strSource.Replace("\t", ""); strSource = strSource.Replace(" ", ""); strSource = strSource.Replace("-->", ""); string[] strnumber = strSource.Split(new string[] { "归属地", "卡类型", "邮 编", "区 号", "更详细", "卡号" }, StringSplitOptions.RemoveEmptyEntries); string[] strnumber1 = null; if (strnumber.Length > 4) { strnumber1 = new string[] { strnumber[1].Trim(), strnumber[2].Trim(), strnumber[3].Trim(), strnumber[4].Trim() }; } return strnumber1; } catch (Exception) { return null; } }
这个例子写是不怎么样,些地方是可以简化的,这个接口而且可以直接使用Xml得到,但我在这里的重点是让一些新手看看方法和思路风凉啊,呵呵 ///<summary> /// 请求的公共类用来向服务器发送请求 ///</summary> ///<param name="strSMSRequest">发送请求的字符串</param> ///<returns>返回的是请求的信息</returns> private static string SMSrequest(string strSMSRequest) { byte[] data = new byte[1024]; string stringData = null; IPHostEntry gist = Dns.GetHostByName("www.110.cn"); IPAddress ip = gist.AddressList[0]; //得到IP IPEndPoint ipEnd = new IPEndPoint(ip, 3121); //默认80端口号 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //使用tcp协议 stream类型 try { socket.Connect(ipEnd); } catch (SocketException ex) { return "Fail to connect server\r\n" + ex.ToString(); } string path = strSMSRequest.ToString().Trim(); StringBuilder buf = new StringBuilder(); //buf.Append("GET ").Append(path).Append(" HTTP/1.0\r\n"); //buf.Append("Content-Type: application/x-www-form-urlencoded\r\n"); //buf.Append("\r\n"); byte[] ms = System.Text.UTF8Encoding.UTF8.GetBytes(buf.ToString()); //提交请求的信息 socket.Send(ms); //接收返回 string strSms = ""; int recv = 0; do { recv = socket.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); //如果请求的页面meta中指定了页面的encoding为gb2312则需要使用对应的Encoding来对字节进行转换() strSms = strSms + stringData; //strSms += recv.ToString(); } while (recv != 0); socket.Shutdown(SocketShutdown.Both); socket.Close(); return strSms; }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论