C#实现http协议通讯类WebClient

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Net;  
  5. using System.Net.Sockets;  
  6. using System.Collections;  
  7. using System.IO;  
  8. using System.Text.RegularExpressions;  
  9. using RE = System.Text.RegularExpressions.Regex;  
  10. using System.Security.Cryptography.X509Certificates;  
  11.    
  12. /*************************************************************************************************************************************************** 
  13.  * *文件名:HttpProc.cs 
  14.  * *创建人:kenter 
  15.  * *日 期:2010.02.23 修改 
  16.  * *描 述:实现HTTP协议中的GET、POST请求 
  17.  * *使 用:HttpProc.WebClient client = new HttpProc.WebClient(); 
  18.             client.Encoding = System.Text.Encoding.Default;//默认编码方式,根据需要设置其他类型 
  19.             client.OpenRead("http://www.baidu.com");//普通get请求 
  20.             MessageBox.Show(client.RespHtml);//获取返回的网页源代码 
  21.             client.DownloadFile("http://www.codepub.com/upload/163album.rar",@"C:\163album.rar");//下载文件 
  22.             client.OpenRead("http://passport.baidu.com/?login","username=zhangsan&password=123456");//提交表单,此处是登录百度的示例 
  23.             client.UploadFile("http://hiup.baidu.com/zhangsan/upload", @"file1=D:\1.mp3");//上传文件 
  24.             client.UploadFile("http://hiup.baidu.com/zhangsan/upload", "folder=myfolder&size=4003550",@"file1=D:\1.mp3");//提交含文本域和文件域的表单 
  25. *****************************************************************************************************************************************************/  
  26.   
  27. namespace HttpProc  
  28. {  
  29.     ///<summary>  
  30.     ///上传事件委托  
  31.     ///</summary>  
  32.     ///<param name="sender"></param>  
  33.     ///<param name="e"></param>  
  34.     public delegate void WebClientUploadEvent(object sender, HttpProc.UploadEventArgs e);  
  35.   
  36.     ///<summary>  
  37.     ///下载事件委托  
  38.     ///</summary>  
  39.     ///<param name="sender"></param>  
  40.     ///<param name="e"></param>  
  41.     public delegate void WebClientDownloadEvent(object sender, HttpProc.DownloadEventArgs e);  
  42.   
  43.   
  44.     ///<summary>  
  45.     ///上传事件参数  
  46.     ///</summary>  
  47.     public struct UploadEventArgs  
  48.     {  
  49.         ///<summary>  
  50.         ///上传数据总大小  
  51.         ///</summary>  
  52.         public long totalBytes;  
  53.         ///<summary>  
  54.         ///已发数据大小  
  55.         ///</summary>  
  56.         public long bytesSent;  
  57.         ///<summary>  
  58.         ///发送进度(0-1)  
  59.         ///</summary>  
  60.         public double sendProgress;  
  61.         ///<summary>  
  62.         ///发送速度Bytes/s  
  63.         ///</summary>  
  64.         public double sendSpeed;  
  65.     }  
  66.   
  67.     ///<summary>  
  68.     ///下载事件参数  
  69.     ///</summary>  
  70.     public struct DownloadEventArgs  
  71.     {  
  72.         ///<summary>  
  73.         ///下载数据总大小  
  74.         ///</summary>  
  75.         public long totalBytes;  
  76.         ///<summary>  
  77.         ///已接收数据大小  
  78.         ///</summary>  
  79.         public long bytesReceived;  
  80.         ///<summary>  
  81.         ///接收数据进度(0-1)  
  82.         ///</summary>  
  83.         public double ReceiveProgress;  
  84.         ///<summary>  
  85.         ///当前缓冲区数据  
  86.         ///</summary>  
  87.         public byte[] receivedBuffer;  
  88.         ///<summary>  
  89.         ///接收速度Bytes/s  
  90.         ///</summary>  
  91.         public double receiveSpeed;  
  92.     }  
  93.   
  94.     ///<summary>  
  95.     ///实现向WEB服务器发送和接收数据  
  96.     ///</summary>  
  97.     public class WebClient  
  98.     {  
  99.         private WebHeaderCollection requestHeaders, responseHeaders;  
  100.         private TcpClient clientSocket;  
  101.         private MemoryStream postStream;  
  102.         private Encoding encoding = Encoding.Default;  
  103.         private const string BOUNDARY = "--HEDAODE--";  
  104.         private const int SEND_BUFFER_SIZE = 10245;  
  105.         private const int RECEIVE_BUFFER_SIZE = 10245;  
  106.         private string cookie = "";  
  107.         private string respHtml = "";  
  108.         private string strRequestHeaders = "";  
  109.         private string strResponseHeaders = "";  
  110.         private int statusCode = 0;  
  111.         private bool isCanceled = false;  
  112.         public event WebClientUploadEvent UploadProgressChanged;  
  113.         public event WebClientDownloadEvent DownloadProgressChanged;  
  114.   
  115.         ///<summary>  
  116.         ///初始化WebClient类  
  117.         ///</summary>  
  118.         public WebClient()  
  119.         {  
  120.             responseHeaders = new WebHeaderCollection();  
  121.             requestHeaders = new WebHeaderCollection();  
  122.         }  
  123.   
  124.         /// <summary>  
  125.         /// 获得字符串中开始和结束字符串中间得值  
  126.         /// </summary>  
  127.         /// <param name="str"></param>  
  128.         /// <param name="s">开始</param>  
  129.         /// <param name="e">结束</param>  
  130.         /// <returns></returns>  
  131.         public string gethtmlContent(string str, string s, string e)  
  132.         {  
  133.             Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);  
  134.             return rg.Match(str).Value;  
  135.         }  
  136.   
  137.         /// <summary>  
  138.         /// 过滤HTML字符  
  139.         /// </summary>  
  140.         /// <param name="source"></param>  
  141.         /// <returns></returns>  
  142.         public string htmlConvert(string source)  
  143.         {  
  144.             string result;  
  145.   
  146.             //remove line breaks,tabs  
  147.             result = source.Replace("\r"" ");  
  148.             result = result.Replace("\n"" ");  
  149.             result = result.Replace("\t"" ");  
  150.   
  151.             //remove the header  
  152.             result = Regex.Replace(result, "(<head>).*(</head>)", string.Empty, RegexOptions.IgnoreCase);  
  153.   
  154.             result = Regex.Replace(result, @"<( )*script([^>])*>""<script>", RegexOptions.IgnoreCase);  
  155.             result = Regex.Replace(result, @"(<script>).*(</script>)", string.Empty, RegexOptions.IgnoreCase);  
  156.   
  157.             //remove all styles  
  158.             result = Regex.Replace(result, @"<( )*style([^>])*>""<style>", RegexOptions.IgnoreCase); //clearing attributes  
  159.             result = Regex.Replace(result, "(<style>).*(</style>)", string.Empty, RegexOptions.IgnoreCase);  
  160.   
  161.             //insert tabs in spaces of <td> tags  
  162.             result = Regex.Replace(result, @"<( )*td([^>])*>"" ", RegexOptions.IgnoreCase);  
  163.   
  164.             //insert line breaks in places of <br> and <li> tags  
  165.             result = Regex.Replace(result, @"<( )*br( )*>""\r", RegexOptions.IgnoreCase);  
  166.             result = Regex.Replace(result, @"<( )*li( )*>""\r", RegexOptions.IgnoreCase);  
  167.   
  168.             //insert line paragraphs in places of <tr> and <p> tags  
  169.             result = Regex.Replace(result, @"<( )*tr([^>])*>""\r\r", RegexOptions.IgnoreCase);  
  170.             result = Regex.Replace(result, @"<( )*p([^>])*>""\r\r", RegexOptions.IgnoreCase);  
  171.   
  172.             //remove anything thats enclosed inside < >  
  173.             result = Regex.Replace(result, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase);  
  174.   
  175.             //replace special characters:  
  176.             result = Regex.Replace(result, @"&amp;""&", RegexOptions.IgnoreCase);  
  177.             result = Regex.Replace(result, @"&nbsp;"" ", RegexOptions.IgnoreCase);  
  178.             result = Regex.Replace(result, @"&lt;""<", RegexOptions.IgnoreCase);  
  179.             result = Regex.Replace(result, @"&gt;"">", RegexOptions.IgnoreCase);  
  180.             result = Regex.Replace(result, @"&(.{2,6});", string.Empty, RegexOptions.IgnoreCase);  
  181.   
  182.             //remove extra line breaks and tabs  
  183.             result = Regex.Replace(result, @" ( )+"" ");  
  184.             result = Regex.Replace(result, "(\r)( )+(\r)""\r\r");  
  185.             result = Regex.Replace(result, @"(\r\r)+""\r\n");  
  186.   
  187.             return result;  
  188.         }  
  189.   
  190.         ///<summary>  
  191.         ///读取指定URL的文本  
  192.         ///</summary>  
  193.         ///<param name="URL">请求的地址</param>  
  194.         ///<returns>服务器响应文本</returns>  
  195.         public string OpenRead(string URL)  
  196.         {  
  197.             requestHeaders.Add("Connection""close");  
  198.             SendRequestData(URL, "GET");  
  199.             return GetHtml();  
  200.         }  
  201.   
  202.   
  203.         //解决证书过期无法访问的问题  
  204.         class CertPolicy : ICertificatePolicy  
  205.         {  
  206.             public bool CheckValidationResult(ServicePoint srvpt, X509Certificate cert, WebRequest req, int certprb)  
  207.             { return true; }  
  208.         }  
  209.   
  210.         ///<summary>  
  211.         ///采用https协议访问网络  
  212.         ///</summary>  
  213.         ///<param name="URL">url地址</param>  
  214.         ///<param name="strPostdata">发送的数据</param>  
  215.         ///<returns></returns>  
  216.         public string OpenReadWithHttps(string URL, string strPostdata)  
  217.         {  
  218.             ServicePointManager.CertificatePolicy = new CertPolicy();  
  219.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);  
  220.             request.CookieContainer = new CookieContainer();  
  221.             request.Method = "POST";  
  222.             request.Accept = "*/*";  
  223.             request.ContentType = "application/x-www-form-urlencoded";  
  224.             byte[] buffer = this.encoding.GetBytes(strPostdata);  
  225.             request.ContentLength = buffer.Length;  
  226.             request.GetRequestStream().Write(buffer, 0, buffer.Length);  
  227.             HttpWebResponse response = (HttpWebResponse)request.GetResponse();  
  228.             StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);  
  229.             this.respHtml = reader.ReadToEnd();  
  230.             foreach (System.Net.Cookie ck in response.Cookies)  
  231.             {  
  232.                 this.cookie += ck.Name + "=" + ck.Value + ";";  
  233.             }  
  234.             reader.Close();  
  235.             return respHtml;  
  236.         }  
  237.   
  238.         ///<summary>  
  239.         ///读取指定URL的文本  
  240.         ///</summary>  
  241.         ///<param name="URL">请求的地址</param>  
  242.         ///<param name="postData">向服务器发送的文本数据</param>  
  243.         ///<returns>服务器响应文本</returns>  
  244.         public string OpenRead(string URL, string postData)  
  245.         {  
  246.             byte[] sendBytes = encoding.GetBytes(postData);  
  247.             postStream = new MemoryStream();  
  248.             postStream.Write(sendBytes, 0, sendBytes.Length);  
  249.   
  250.             requestHeaders.Add("Content-Length", postStream.Length.ToString());  
  251.             requestHeaders.Add("Content-Type""application/x-www-form-urlencoded");  
  252.             requestHeaders.Add("Connection""close");  
  253.   
  254.             SendRequestData(URL, "POST");  
  255.             return GetHtml();  
  256.         }  
  257.   
  258.   
  259.         ///<summary>  
  260.         ///读取指定URL的流  
  261.         ///</summary>  
  262.         ///<param name="URL">请求的地址</param>  
  263.         ///<param name="postData">向服务器发送的数据</param>  
  264.         ///<returns>服务器响应流</returns>  
  265.         public Stream GetStream(string URL, string postData)  
  266.         {  
  267.             byte[] sendBytes = encoding.GetBytes(postData);  
  268.             postStream = new MemoryStream();  
  269.             postStream.Write(sendBytes, 0, sendBytes.Length);  
  270.   
  271.             requestHeaders.Add("Content-Length", postStream.Length.ToString());  
  272.             requestHeaders.Add("Content-Type""application/x-www-form-urlencoded");  
  273.             requestHeaders.Add("Connection""close");  
  274.   
  275.             SendRequestData(URL, "POST");  
  276.   
  277.             MemoryStream ms = new MemoryStream();  
  278.             SaveNetworkStream(ms);  
  279.             return ms;  
  280.         }  
  281.   
  282.   
  283.         ///<summary>  
  284.         ///上传文件到服务器  
  285.         ///</summary>  
  286.         ///<param name="URL">请求的地址</param>  
  287.         ///<param name="fileField">文件域(格式如:file1=C:\test.mp3&file2=C:\test.jpg)</param>  
  288.         ///<returns>服务器响应文本</returns>  
  289.         public string UploadFile(string URL, string fileField)  
  290.         {  
  291.             return UploadFile(URL, "", fileField);  
  292.         }  
  293.   
  294.         ///<summary>  
  295.         ///上传文件和数据到服务器  
  296.         ///</summary>  
  297.         ///<param name="URL">请求地址</param>  
  298.         ///<param name="textField">文本域(格式为:name1=value1&name2=value2)</param>  
  299.         ///<param name="fileField">文件域(格式如:file1=C:\test.mp3&file2=C:\test.jpg)</param>  
  300.         ///<returns>服务器响应文本</returns>  
  301.         public string UploadFile(string URL, string textField, string fileField)  
  302.         {  
  303.             postStream = new MemoryStream();  
  304.   
  305.             if (textField != "" && fileField != "")  
  306.             {  
  307.                 WriteTextField(textField);  
  308.                 WriteFileField(fileField);  
  309.             }  
  310.             else if (fileField != "")  
  311.             {  
  312.                 WriteFileField(fileField);  
  313.             }  
  314.             else if (textField != "")  
  315.             {  
  316.                 WriteTextField(textField);  
  317.             }  
  318.             else  
  319.                 throw new Exception("文本域和文件域不能同时为空。");  
  320.   
  321.             //写入结束标记  
  322.             byte[] buffer = encoding.GetBytes("--" + BOUNDARY + "--\r\n");  
  323.             postStream.Write(buffer, 0, buffer.Length);  
  324.   
  325.             //添加请求标头  
  326.             requestHeaders.Add("Content-Length", postStream.Length.ToString());  
  327.             requestHeaders.Add("Content-Type""multipart/form-data; boundary=" + BOUNDARY);  
  328.             requestHeaders.Add("Connection""Keep-Alive");  
  329.   
  330.             //发送请求数据  
  331.             SendRequestData(URL, "POST"true);  
  332.   
  333.             //返回响应文本  
  334.             return GetHtml();  
  335.         }  
  336.   
  337.   
  338.         ///<summary>  
  339.         ///分析文本域,添加到请求流  
  340.         ///</summary>  
  341.         ///<param name="textField">文本域</param>  
  342.         private void WriteTextField(string textField)  
  343.         {  
  344.             string[] strArr = RE.Split(textField, "&");  
  345.             textField = "";  
  346.             foreach (string var in strArr)  
  347.             {  
  348.                 Match M = RE.Match(var, "([^=]+)=(.+)");  
  349.                 textField += "--" + BOUNDARY + "\r\n";  
  350.                 textField += "Content-Disposition: form-data; name=\"" + M.Groups[1].Value + "\"\r\n\r\n" + M.Groups[2].Value + "\r\n";  
  351.             }  
  352.             byte[] buffer = encoding.GetBytes(textField);  
  353.             postStream.Write(buffer, 0, buffer.Length);  
  354.         }  
  355.   
  356.         ///<summary>  
  357.         ///分析文件域,添加到请求流  
  358.         ///</summary>  
  359.         ///<param name="fileField">文件域</param>  
  360.         private void WriteFileField(string fileField)  
  361.         {  
  362.             string filePath = "";  
  363.             int count = 0;  
  364.             string[] strArr = RE.Split(fileField, "&");  
  365.             foreach (string var in strArr)  
  366.             {  
  367.                 Match M = RE.Match(var, "([^=]+)=(.+)");  
  368.                 filePath = M.Groups[2].Value;  
  369.                 fileField = "--" + BOUNDARY + "\r\n";  
  370.                 fileField += "Content-Disposition: form-data; name=\"" + M.Groups[1].Value + "\"; filename=\"" + Path.GetFileName(filePath) + "\"\r\n";  
  371.                 fileField += "Content-Type: image/jpeg\r\n\r\n";  
  372.   
  373.                 byte[] buffer = encoding.GetBytes(fileField);  
  374.                 postStream.Write(buffer, 0, buffer.Length);  
  375.   
  376.                 //添加文件数据  
  377.                 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
  378.                 buffer = new byte[50000];  
  379.   
  380.                 do  
  381.                 {  
  382.                     count = fs.Read(buffer, 0, buffer.Length);  
  383.                     postStream.Write(buffer, 0, count);  
  384.   
  385.                 } while (count > 0);  
  386.   
  387.                 fs.Close();  
  388.                 fs.Dispose();  
  389.                 fs = null;  
  390.   
  391.                 buffer = encoding.GetBytes("\r\n");  
  392.                 postStream.Write(buffer, 0, buffer.Length);  
  393.             }  
  394.         }  
  395.   
  396.         ///<summary>  
  397.         ///从指定URL下载数据流  
  398.         ///</summary>  
  399.         ///<param name="URL">请求地址</param>  
  400.         ///<returns>数据流</returns>  
  401.         public Stream DownloadData(string URL)  
  402.         {  
  403.             requestHeaders.Add("Connection""close");  
  404.             SendRequestData(URL, "GET");  
  405.             MemoryStream ms = new MemoryStream();  
  406.             SaveNetworkStream(ms, true);  
  407.             return ms;  
  408.         }  
  409.   
  410.   
  411.         ///<summary>  
  412.         ///从指定URL下载文件  
  413.         ///</summary>  
  414.         ///<param name="URL">文件URL地址</param>  
  415.         ///<param name="fileName">文件保存路径,含文件名(如:C:\test.jpg)</param>  
  416.         public void DownloadFile(string URL, string fileName)  
  417.         {  
  418.             requestHeaders.Add("Connection""close");  
  419.             SendRequestData(URL, "GET");  
  420.             FileStream fs = new FileStream(fileName, FileMode.Create);  
  421.             SaveNetworkStream(fs, true);  
  422.             fs.Close();  
  423.             fs = null;  
  424.         }  
  425.   
  426.         ///<summary>  
  427.         ///向服务器发送请求  
  428.         ///</summary>  
  429.         ///<param name="URL">请求地址</param>  
  430.         ///<param name="method">POST或GET</param>  
  431.         ///<param name="showProgress">是否显示上传进度</param>  
  432.         private void SendRequestData(string URL, string method, bool showProgress)  
  433.         {  
  434.             clientSocket = new TcpClient();  
  435.             Uri URI = new Uri(URL);  
  436.             clientSocket.Connect(URI.Host, URI.Port);  
  437.   
  438.             requestHeaders.Add("Host", URI.Host);  
  439.             byte[] request = GetRequestHeaders(method + " " + URI.PathAndQuery + " HTTP/1.1");  
  440.             clientSocket.Client.Send(request);  
  441.   
  442.             //若有实体内容就发送它  
  443.             if (postStream != null)  
  444.             {  
  445.                 byte[] buffer = new byte[SEND_BUFFER_SIZE];  
  446.                 int count = 0;  
  447.                 Stream sm = clientSocket.GetStream();  
  448.                 postStream.Position = 0;  
  449.   
  450.                 UploadEventArgs e = new UploadEventArgs();  
  451.                 e.totalBytes = postStream.Length;  
  452.                 System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();//计时器  
  453.                 timer.Start();  
  454.                 do  
  455.                 {  
  456.                     //如果取消就推出  
  457.                     if (isCanceled) { break; }  
  458.   
  459.                     //读取要发送的数据  
  460.                     count = postStream.Read(buffer, 0, buffer.Length);  
  461.                     //发送到服务器  
  462.                     sm.Write(buffer, 0, count);  
  463.   
  464.                     //是否显示进度  
  465.                     if (showProgress)  
  466.                     {  
  467.                         //触发事件  
  468.                         e.bytesSent += count;  
  469.                         e.sendProgress = (double)e.bytesSent / (double)e.totalBytes;  
  470.                         double t = timer.ElapsedMilliseconds / 1000;  
  471.                         t = t <= 0 ? 1 : t;  
  472.                         e.sendSpeed = (double)e.bytesSent / t;  
  473.                         if (UploadProgressChanged != null) { UploadProgressChanged(this, e); }  
  474.                     }  
  475.   
  476.                 } while (count > 0);  
  477.                 timer.Stop();  
  478.                 postStream.Close();  
  479.                 //postStream.Dispose();  
  480.                 postStream = null;  
  481.   
  482.             }//end if  
  483.   
  484.         }  
  485.   
  486.         ///<summary>  
  487.         ///向服务器发送请求  
  488.         ///</summary>  
  489.         ///<param name="URL">请求URL地址</param>  
  490.         ///<param name="method">POST或GET</param>  
  491.         private void SendRequestData(string URL, string method)  
  492.         {  
  493.             SendRequestData(URL, method, false);  
  494.         }  
  495.   
  496.   
  497.         ///<summary>  
  498.         ///获取请求头字节数组  
  499.         ///</summary>  
  500.         ///<param name="request">POST或GET请求</param>  
  501.         ///<returns>请求头字节数组</returns>  
  502.         private byte[] GetRequestHeaders(string request)  
  503.         {  
  504.             requestHeaders.Add("Accept""*/*");  
  505.             requestHeaders.Add("Accept-Language""zh-cn");  
  506.             requestHeaders.Add("User-Agent""Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");  
  507.   
  508.             string headers = request + "\r\n";  
  509.   
  510.             foreach (string key in requestHeaders)  
  511.             {  
  512.                 headers += key + ":" + requestHeaders[key] + "\r\n";  
  513.             }  
  514.   
  515.             //有Cookie就带上Cookie  
  516.             if (cookie != "") { headers += "Cookie:" + cookie + "\r\n"; }  
  517.   
  518.             //空行,请求头结束  
  519.             headers += "\r\n";  
  520.   
  521.             strRequestHeaders = headers;  
  522.             requestHeaders.Clear();  
  523.             return encoding.GetBytes(headers);  
  524.         }  
  525.   
  526.   
  527.   
  528.         ///<summary>  
  529.         ///获取服务器响应文本  
  530.         ///</summary>  
  531.         ///<returns>服务器响应文本</returns>  
  532.         private string GetHtml()  
  533.         {  
  534.             MemoryStream ms = new MemoryStream();  
  535.             SaveNetworkStream(ms);//将网络流保存到内存流  
  536.             StreamReader sr = new StreamReader(ms, encoding);  
  537.             respHtml = sr.ReadToEnd();  
  538.             sr.Close(); ms.Close();  
  539.             return respHtml;  
  540.         }  
  541.   
  542.         ///<summary>  
  543.         ///将网络流保存到指定流  
  544.         ///</summary>  
  545.         ///<param name="toStream">保存位置</param>  
  546.         ///<param name="needProgress">是否显示进度</param>  
  547.         private void SaveNetworkStream(Stream toStream, bool showProgress)  
  548.         {  
  549.             //获取要保存的网络流  
  550.             NetworkStream NetStream = clientSocket.GetStream();  
  551.   
  552.             byte[] buffer = new byte[RECEIVE_BUFFER_SIZE];  
  553.             int count = 0, startIndex = 0;  
  554.   
  555.             MemoryStream ms = new MemoryStream();  
  556.             for (int i = 0; i < 3; i++)  
  557.             {  
  558.                 count = NetStream.Read(buffer, 0500);  
  559.                 ms.Write(buffer, 0, count);  
  560.             }  
  561.   
  562.             if (ms.Length == 0) { NetStream.Close(); throw new Exception("远程服务器没有响应"); }  
  563.   
  564.             buffer = ms.GetBuffer();  
  565.             count = (int)ms.Length;  
  566.   
  567.             GetResponseHeader(buffer, out startIndex);//分析响应,获取响应头和响应实体  
  568.             count -= startIndex;  
  569.             toStream.Write(buffer, startIndex, count);  
  570.   
  571.             DownloadEventArgs e = new DownloadEventArgs();  
  572.   
  573.             if (responseHeaders["Content-Length"] != null)  
  574.             { e.totalBytes = long.Parse(responseHeaders["Content-Length"]); }  
  575.             else  
  576.             { e.totalBytes = -1; }  
  577.   
  578.             //启动计时器  
  579.             System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();  
  580.             timer.Start();  
  581.   
  582.             do  
  583.             {  
  584.                 //如果取消就推出  
  585.                 if (isCanceled) { break; }  
  586.   
  587.                 //显示下载进度  
  588.                 if (showProgress)  
  589.                 {  
  590.                     e.bytesReceived += count;  
  591.                     e.ReceiveProgress = (double)e.bytesReceived / (double)e.totalBytes;  
  592.   
  593.                     byte[] tempBuffer = new byte[count];  
  594.                     Array.Copy(buffer, startIndex, tempBuffer, 0, count);  
  595.                     e.receivedBuffer = tempBuffer;  
  596.   
  597.                     double t = (timer.ElapsedMilliseconds + 0.1) / 1000;  
  598.                     e.receiveSpeed = (double)e.bytesReceived / t;  
  599.   
  600.                     startIndex = 0;  
  601.                     if (DownloadProgressChanged != null) { DownloadProgressChanged(this, e); }  
  602.                 }  
  603.   
  604.                 //读取网路数据到缓冲区  
  605.                 count = NetStream.Read(buffer, 0, buffer.Length);  
  606.   
  607.                 //将缓存区数据保存到指定流  
  608.                 toStream.Write(buffer, 0, count);  
  609.             } while (count > 0);  
  610.   
  611.             timer.Stop();//关闭计时器  
  612.   
  613.             if (responseHeaders["Content-Length"] != null)  
  614.             {  
  615.                 toStream.SetLength(long.Parse(responseHeaders["Content-Length"]));  
  616.             }  
  617.             //else  
  618.             //{  
  619.             //    toStream.SetLength(toStream.Length);  
  620.             //    responseHeaders.Add("Content-Length", toStream.Length.ToString());//添加响应标头  
  621.             //}  
  622.   
  623.             toStream.Position = 0;  
  624.   
  625.             //关闭网络流和网络连接  
  626.             NetStream.Close();  
  627.             clientSocket.Close();  
  628.         }  
  629.   
  630.   
  631.         ///<summary>  
  632.         ///将网络流保存到指定流  
  633.         ///</summary>  
  634.         ///<param name="toStream">保存位置</param>  
  635.         private void SaveNetworkStream(Stream toStream)  
  636.         {  
  637.             SaveNetworkStream(toStream, false);  
  638.         }  
  639.   
  640.   
  641.   
  642.         ///<summary>  
  643.         ///分析响应流,去掉响应头  
  644.         ///</summary>  
  645.         ///<param name="buffer"></param>  
  646.         private void GetResponseHeader(byte[] buffer, out int startIndex)  
  647.         {  
  648.             responseHeaders.Clear();  
  649.             string html = encoding.GetString(buffer);  
  650.             StringReader sr = new StringReader(html);  
  651.   
  652.             int start = html.IndexOf("\r\n\r\n") + 4;//找到空行位置  
  653.             strResponseHeaders = html.Substring(0, start);//获取响应头文本  
  654.   
  655.             //获取响应状态码  
  656.             //  
  657.             if (sr.Peek() > -1)  
  658.             {  
  659.                 //读第一行字符串  
  660.                 string line = sr.ReadLine();  
  661.   
  662.                 //分析此行字符串,获取服务器响应状态码  
  663.                 Match M = RE.Match(line, @"\d\d\d");  
  664.                 if (M.Success)  
  665.                 {  
  666.                     statusCode = int.Parse(M.Value);  
  667.                 }  
  668.             }  
  669.   
  670.             //获取响应头  
  671.             //  
  672.             while (sr.Peek() > -1)  
  673.             {  
  674.                 //读一行字符串  
  675.                 string line = sr.ReadLine();  
  676.   
  677.                 //若非空行  
  678.                 if (line != "")  
  679.                 {  
  680.                     //分析此行字符串,获取响应标头  
  681.                     Match M = RE.Match(line, "([^:]+):(.+)");  
  682.                     if (M.Success)  
  683.                     {  
  684.                         try  
  685.                         {        //添加响应标头到集合  
  686.                             responseHeaders.Add(M.Groups[1].Value.Trim(), M.Groups[2].Value.Trim());  
  687.                         }  
  688.                         catch  
  689.                         { }  
  690.   
  691.   
  692.                         //获取Cookie  
  693.                         if (M.Groups[1].Value == "Set-Cookie")  
  694.                         {  
  695.                             M = RE.Match(M.Groups[2].Value, "[^=]+=[^;]+");  
  696.                             cookie += M.Value.Trim() + ";";  
  697.                         }  
  698.                     }  
  699.   
  700.                 }  
  701.                 //若是空行,代表响应头结束响应实体开始。(响应头和响应实体间用一空行隔开)  
  702.                 else  
  703.                 {  
  704.                     //如果响应头中没有实体大小标头,尝试读响应实体第一行获取实体大小  
  705.                     if (responseHeaders["Content-Length"] == null && sr.Peek() > -1)  
  706.                     {  
  707.                         //读响应实体第一行  
  708.                         line = sr.ReadLine();  
  709.   
  710.                         //分析此行看是否包含实体大小  
  711.                         Match M = RE.Match(line, "~[0-9a-fA-F]{1,15}");  
  712.   
  713.                         if (M.Success)  
  714.                         {  
  715.                             //将16进制的实体大小字符串转换为10进制  
  716.                             int length = int.Parse(M.Value, System.Globalization.NumberStyles.AllowHexSpecifier);  
  717.                             responseHeaders.Add("Content-Length", length.ToString());//添加响应标头  
  718.                             strResponseHeaders += M.Value + "\r\n";  
  719.                         }  
  720.                     }  
  721.                     break;//跳出循环   
  722.                 }//End If  
  723.             }//End While  
  724.   
  725.             sr.Close();  
  726.   
  727.             //实体开始索引  
  728.             startIndex = encoding.GetBytes(strResponseHeaders).Length;  
  729.         }  
  730.   
  731.   
  732.         ///<summary>  
  733.         ///取消上传或下载,要继续开始请调用Start方法  
  734.         ///</summary>  
  735.         public void Cancel()  
  736.         {  
  737.             isCanceled = true;  
  738.         }  
  739.   
  740.         ///<summary>  
  741.         ///启动上传或下载,要取消请调用Cancel方法  
  742.         ///</summary>  
  743.         public void Start()  
  744.         {  
  745.             isCanceled = false;  
  746.         }  
  747.   
  748.         //*************************************************************  
  749.         //以下为属性  
  750.         //*************************************************************  
  751.   
  752.         ///<summary>  
  753.         ///获取或设置请求头  
  754.         ///</summary>  
  755.         public WebHeaderCollection RequestHeaders  
  756.         {  
  757.             set { requestHeaders = value; }  
  758.             get { return requestHeaders; }  
  759.         }  
  760.   
  761.         ///<summary>  
  762.         ///获取响应头集合  
  763.         ///</summary>  
  764.         public WebHeaderCollection ResponseHeaders  
  765.         {  
  766.             get { return responseHeaders; }  
  767.         }  
  768.   
  769.         ///<summary>  
  770.         ///获取请求头文本  
  771.         ///</summary>  
  772.         public string StrRequestHeaders  
  773.         {  
  774.             get { return strRequestHeaders; }  
  775.         }  
  776.   
  777.         ///<summary>  
  778.         ///获取响应头文本  
  779.         ///</summary>  
  780.         public string StrResponseHeaders  
  781.         {  
  782.             get { return strResponseHeaders; }  
  783.         }  
  784.   
  785.         ///<summary>  
  786.         ///获取或设置Cookie  
  787.         ///</summary>  
  788.         public string Cookie  
  789.         {  
  790.             set { cookie = value; }  
  791.             get { return cookie; }  
  792.         }  
  793.   
  794.         ///<summary>  
  795.         ///获取或设置编码方式(默认为系统默认编码方式)  
  796.         ///</summary>  
  797.         public Encoding Encoding  
  798.         {  
  799.             set { encoding = value; }  
  800.             get { return encoding; }  
  801.         }  
  802.   
  803.         ///<summary>  
  804.         ///获取服务器响应文本  
  805.         ///</summary>  
  806.         public string RespHtml  
  807.         {  
  808.             get { return respHtml; }  
  809.         }  
  810.   
  811.   
  812.         ///<summary>  
  813.         ///获取服务器响应状态码  
  814.         ///</summary>  
  815.         public int StatusCode  
  816.         {  
  817.             get { return statusCode; }  
  818.         }  
  819.     }  
  820. }  

 

 

 

 

Java代码 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Text.RegularExpressions;  
  10. using HttpProc;  
  11.   
  12.   
  13. namespace zzbdsProject  
  14. {  
  15.     public partial class Form1 : Form  
  16.     {  
  17.         public Form1()  
  18.         {  
  19.             InitializeComponent();  
  20.         }  
  21.   
  22.         //查询alexa排名  
  23.         private void button1_Click(object sender, EventArgs e)  
  24.         {  
  25.             Console.WriteLine(DateTime.Now.ToLongTimeString());  
  26.             WebClient webClient = new WebClient();  
  27.             //默认编码方式,根据需要设置其他类型  
  28.             webClient.Encoding = System.Text.Encoding.UTF8;  
  29.             string domainName = "ads8.com";  
  30.             string html;  
  31.             html = webClient.OpenRead(@"http://cn.alexa.com/siteinfo/www." + domainName);  
  32.             Console.WriteLine("名称:" + webClient.gethtmlContent(html, "关于 "": "));  
  33.             Console.WriteLine("alexa世界排名:" + webClient.gethtmlContent(html, "margin-bottom:-2px;\"/> ""</a>"));  
  34.             Console.WriteLine("中国排名:" + webClient.gethtmlContent(html, "<span class=\"geo_number descbold\">""</span>"));  
  35.             Console.WriteLine("反向链接:" + webClient.gethtmlContent(html, "<!--<a href=\"/site/linksin/" + domainName + "\">-->""<!--</a>-->"));  
  36.             Console.WriteLine("上线日期:" + webClient.gethtmlContent(html, "<td class=\"end\">\n      <div class=\"data\">""</a></div>"));  
  37.   
  38.             Console.WriteLine("昨日:" + webClient.gethtmlContent(html, "<th>昨日</th><td>""</td>"));  
  39.             Console.WriteLine("最近七天平均:" + webClient.gethtmlContent(html, "<th>最近七天平均</th><td>""</td>"));  
  40.             Console.WriteLine("最近一月平均:" + webClient.gethtmlContent(html, "<th>最近一月平均</th><td>""</td>"));  
  41.             Console.WriteLine("最近三月平均:" + webClient.gethtmlContent(html, "<th>最近三月平均</th><td>""</td>"));  
  42.             Console.WriteLine("最近三月改变量:" + webClient.htmlConvert(webClient.gethtmlContent(html, "<th>最近三月改变量</th><td>""</td>")));  
  43.             Console.WriteLine(DateTime.Now.ToLongTimeString());  
  44.         }  
  45.   
  46.         //查询搜索引擎收录  
  47.         private void button2_Click(object sender, EventArgs e)  
  48.         {  
  49.             Console.WriteLine(DateTime.Now.ToLongTimeString());  
  50.             WebClient webClient = new WebClient();  
  51.   
  52.             string domainName = "0756888.com";  
  53.             string html;  
  54.   
  55.             //Baidu收录查询  
  56.             webClient.Encoding = System.Text.Encoding.Default;  
  57.   
  58.             html = webClient.OpenRead(@"http://www.baidu.com/s?wd=site%3Awww." + domainName);  
  59.             Console.WriteLine("百度总收录数:" + webClient.gethtmlContent(html, "找到相关网页""篇,用时"));  
  60.   
  61.             html = webClient.OpenRead(@"http://www.baidu.com/s?wd=domain%3Awww." + domainName);  
  62.             Console.WriteLine("百度反向链接数:" + webClient.gethtmlContent(html, "找到相关网页""篇,用时"));  
  63.   
  64.             html = webClient.OpenRead(@"http://www.baidu.com/s?q1=site%3Awww." + domainName  
  65.                 + "&q2=&q3=&q4=&rn=10&lm=1&ct=0&ft=&q5=&q6=&tn=baiduadv");  
  66.             Console.WriteLine("百度最近一天收录数:" + webClient.gethtmlContent(html, "找到相关网页""篇,用时"));  
  67.   
  68.             html = webClient.OpenRead(@"http://www.baidu.com/s?q1=site%3Awww." + domainName  
  69.                 + "&q2=&q3=&q4=&rn=10&lm=7&ct=0&ft=&q5=&q6=&tn=baiduadv");  
  70.             Console.WriteLine("百度最近一周收录数:" + webClient.gethtmlContent(html, "找到相关网页""篇,用时"));  
  71.   
  72.             html = webClient.OpenRead(@"http://www.baidu.com/s?q1=site%3Awww." + domainName  
  73.                 + "&q2=&q3=&q4=&rn=10&lm=7&ct=0&ft=&q5=&q6=&tn=baiduadv");  
  74.             Console.WriteLine("百度最近一月收录数:" + webClient.gethtmlContent(html, "找到相关网页""篇,用时"));  
  75.   
  76.             html = webClient.OpenRead(@"http://www.baidu.com/s?q1=domain%3Awww." + domainName  
  77.                 + "&q2=&q3=&q4=&rn=10&lm=7&ct=0&ft=&q5=&q6=&tn=baiduadv");  
  78.             Console.WriteLine("百度最近一月反向链接数:" + webClient.gethtmlContent(html, "找到相关网页""篇,用时"));  
  79.   
  80.   
  81.             //Google.cn收录查询  
  82.             webClient.Encoding = System.Text.Encoding.UTF8;  
  83.   
  84.             html = webClient.OpenRead(@"http://www.google.cn/search?as_q=site%3Awww." + domainName + "&hl=zh-CN&" +  
  85.                 "newwindow=1&num=10&btnG=Google+%E6%90%9C%E7%B4%A2&as_epq=&as_oq=&as_eq=&lr=&cr=&as_ft=i&as_filetype=" +  
  86.                 "&as_qdr=all&as_occt=any&as_dt=i&as_sitesearch=&as_rights=");  
  87.             Console.WriteLine("Google.cn总收录数:" + webClient.gethtmlContent(html, "获得约 <b>""</b> 条结果"));  
  88.   
  89.             html = webClient.OpenRead(@"http://www.google.cn/search?as_q=domain%3Awww." + domainName + "&hl=zh-CN&" +  
  90.                 "newwindow=1&num=10&btnG=Google+%E6%90%9C%E7%B4%A2&as_epq=&as_oq=&as_eq=&lr=&cr=&as_ft=i&as_filetype=" +  
  91.                 "&as_qdr=all&as_occt=any&as_dt=i&as_sitesearch=&as_rights=");  
  92.             Console.WriteLine("Google.cn总反向链接数:" + webClient.gethtmlContent(html, "获得约 <b>""</b> 条结果"));  
  93.   
  94.             html = webClient.OpenRead(@"http://www.google.cn/search?as_q=site%3Awww." + domainName +  
  95.                 "&hl=zh-CN&newwindow=1&num=10&btnG=Google+%E6%90%9C%E7%B4%A2&as_epq=&as_oq=&as_eq=&lr=&cr=&as_ft=i&as_filetype" +  
  96.                 "=&as_qdr=d&as_occt=any&as_dt=i&as_sitesearch=&as_rights=");  
  97.             Console.WriteLine("Google.cn最近一天收录数:" + webClient.gethtmlContent(html, "获得约 <b>""</b> 条结果"));  
  98.   
  99.             html = webClient.OpenRead(@"http://www.google.cn/search?as_q=site%3Awww." + domainName +  
  100.                 "&hl=zh-CN&newwindow=1&num=10&btnG=Google+%E6%90%9C%E7%B4%A2&as_epq=&as_oq=&as_eq=&lr=&cr=&as_ft=i&as_filetype" +  
  101.                 "=&as_qdr=w&as_occt=any&as_dt=i&as_sitesearch=&as_rights=");  
  102.             Console.WriteLine("Google.cn最近一周收录数:" + webClient.gethtmlContent(html, "获得约 <b>""</b> 条结果"));  
  103.   
  104.             html = webClient.OpenRead(@"http://www.google.cn/search?as_q=site%3Awww." + domainName +  
  105.                 "&hl=zh-CN&newwindow=1&num=10&btnG=Google+%E6%90%9C%E7%B4%A2&as_epq=&as_oq=&as_eq=&lr=&cr=&as_ft=i&as_filetype" +  
  106.                 "=&as_qdr=m&as_occt=any&as_dt=i&as_sitesearch=&as_rights=");  
  107.             Console.WriteLine("Google.cn最近一月收录数:" + webClient.gethtmlContent(html, "获得约 <b>""</b> 条结果"));  
  108.   
  109.             Console.WriteLine(DateTime.Now.ToLongTimeString());  
  110.         }      
  111.     }  
  112. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值