项目 - 通用扩展库 - 基础库 - WoodCoal.Base.Http.Client

WoodCoal.Base.Http.Client

本文最后更新时间:2009/03/08

  1. '--------------------------------------------------  
  2. '  
  3. '   木炭通用扩展库 - 基础库  
  4. '  
  5. '   namespace: WoodCoal.Base.HTTP.Utility  
  6. '   author: 木炭(WoodCoal)  
  7. '   homepage: http://www.woodcoal.cn/  
  8. '   memo: 本版本以 WebClient 为基础扩展的功能  
  9. '   release: 2009-03-08  
  10. '  
  11. '--------------------------------------------------  
  12.  
  13. Namespace HTTP  
  14.     Public Class Client  
  15.         ''' <summary>HTTP 请求对象</summary>  
  16.         Private oHttp As Net.WebClient  
  17.  
  18.         ''' <summary>Url 地址</summary>  
  19.         Private xUrl As Uri = Nothing 
  20.  
  21.         ''' <summary>保持文件路径</summary>  
  22.         Private xFilePath As String = "" 
  23.  
  24.         ''' <summary>文件名称</summary>  
  25.         Private xFileName(1) As String 
  26.  
  27.         ''' <summary>上传的内容</summary>  
  28.         Private xPostString As String 
  29.  
  30.         ''' <summary>页面语言</summary>  
  31.         Private xCharset As String = "" 
  32.  
  33.         ''' <summary>浏览器头</summary>  
  34.         Private xUserAgent As String = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" 
  35.  
  36.         ''' <summary>Cookies 数据</summary>  
  37.         Private xCookies As String = "" 
  38.  
  39.         Private Disposed As Boolean = False 
  40.  
  41.         Public Sub New()  
  42.             Reset()  
  43.         End Sub 
  44.  
  45.         Public Sub Dispose()  
  46.             On Error Resume Next 
  47.  
  48.             If Not Disposed Then 
  49.                 oHttp.Dispose()  
  50.                 oHttp = Nothing 
  51.  
  52.                 Disposed = True 
  53.             End If 
  54.         End Sub 
  55.  
  56.         Protected Overrides Sub Finalize()  
  57.             Me.Dispose()  
  58.             MyBase.Finalize()  
  59.         End Sub 
  60.  
  61.         ''' <summary>重设所有操作</summary>  
  62.         Public Sub Reset()  
  63.             If oHttp IsNot Nothing Then 
  64.                 oHttp.Dispose()  
  65.                 oHttp = Nothing 
  66.             End If 
  67.             oHttp = New Net.WebClient  
  68.  
  69.             oHttp.Headers.Add(Net.HttpRequestHeader.Accept, "*/*")  
  70.             'oHttp.Headers.Add(Net.HttpRequestHeader.AcceptLanguage, "zh-cn")  
  71.             'oHttp.Headers.Add(Net.HttpRequestHeader.AcceptEncoding, "gzip, deflate")  
  72.             xUrl = Nothing 
  73.             xCharset = "" 
  74.             xUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)" 
  75.             xCookies = "" 
  76.             xPostString = "" 
  77.  
  78.             xFilePath = "" 
  79.  
  80.             xFileName(0) = "" 
  81.             xFileName(1) = "" 
  82.         End Sub 
  83.  
  84.         '-------------------------------------------------------------------------------  
  85.  
  86.         ''' <summary>需要操作的URL</summary>  
  87.         Public Overloads Property Url() As String 
  88.             Get 
  89.                 Return xUrl.AbsoluteUri  
  90.             End Get 
  91.             Set(ByVal Value As String)  
  92.                 Try 
  93.                     xUrl = New Uri(Value)  
  94.                 Catch ex As Exception  
  95.                     xUrl = Nothing 
  96.                 End Try 
  97.             End Set 
  98.         End Property 
  99.  
  100.         ''' <summary>设置来源地址</summary>  
  101.         Public WriteOnly Property Referer() As String 
  102.             Set(ByVal Value As String)  
  103.                 oHttp.Headers.Add(Net.HttpRequestHeader.Referer, Value)  
  104.             End Set 
  105.         End Property 
  106.  
  107.         ''' <summary>操作页面的语言编码</summary>  
  108.         Public Property Charset() As String 
  109.             Get 
  110.                 Return xCharset  
  111.             End Get 
  112.             Set(ByVal Value As String)  
  113.                 xCharset = Value  
  114.                 'If xCharset.Length < 3 Then xCharset = "UTF-8"  
  115.             End Set 
  116.         End Property 
  117.  
  118.         ''' <summary>模拟浏览器名称</summary>  
  119.         Public Property UserAgent() As String 
  120.             Get 
  121.                 Return xUserAgent  
  122.             End Get 
  123.             Set(ByVal Value As String)  
  124.                 If Not String.IsNullOrEmpty(Value) Then xUserAgent = Value  
  125.             End Set 
  126.         End Property 
  127.  
  128.  
  129.         ''' <summary>文件保存路径</summary>  
  130.         ''' <param name="IsCreatedDir">路径不存在时,是否自动创建</param>  
  131.         Public WriteOnly Property FilePath(Optional ByVal IsCreatedDir As Boolean = FalseAs String 
  132.             Set(ByVal Value As String)  
  133.                 xFilePath = Files.Unti.TruePath(Value, IsCreatedDir)  
  134.             End Set 
  135.         End Property 
  136.  
  137.         ''' <summary>文件保存路径</summary>  
  138.         Public Property FileName() As String 
  139.             Get 
  140.                 Return xFileName(1)  
  141.             End Get 
  142.             Set(ByVal value As String)  
  143.                 xFileName(0) = value  
  144.             End Set 
  145.         End Property 
  146.  
  147.         ''' <summary>设置获取Cookies</summary>  
  148.         Public Property Cookies() As String 
  149.             Get 
  150.                 On Error Resume Next 
  151.                 Dim Value As String = oHttp.ResponseHeaders(Net.HttpResponseHeader.SetCookie)  
  152.                 If String.IsNullOrEmpty(Value) Then Value = xCookies  
  153.                 Return Value  
  154.             End Get 
  155.             Set(ByVal value As String)  
  156.                 xCookies = value.Replace(vbCrLf, ";")  
  157.                 oHttp.Headers.Add(Net.HttpRequestHeader.Cookie, xCookies)  
  158.             End Set 
  159.         End Property 
  160.  
  161.         ''' <summary>设置获取页面请求头</summary>  
  162.         Public Overloads ReadOnly Property Header() As Net.WebHeaderCollection  
  163.             Get 
  164.                 Return oHttp.ResponseHeaders  
  165.             End Get 
  166.         End Property 
  167.  
  168.         ''' <summary>设置获取页面请求头</summary>  
  169.         ''' <param name="key">头名称</param>  
  170.         Public Overloads Property Header(ByVal key As StringAs String 
  171.             Get 
  172.                 Return oHttp.ResponseHeaders(key)  
  173.             End Get 
  174.             Set(ByVal value As String)  
  175.                 oHttp.Headers.Add(key, value)  
  176.             End Set 
  177.         End Property 
  178.  
  179.         ''' <summary>获取附件名称</summary>  
  180.         Public ReadOnly Property Attachment() As String 
  181.             Get 
  182.                 Dim Value As String = oHttp.ResponseHeaders("Content-Disposition")  
  183.  
  184.                 If Not String.IsNullOrEmpty(Value) AndAlso Value.ToLower.Contains("filename="Then 
  185.                     Value = Split(Value, "filename=")(1)  
  186.                     Value = Value.Replace("""""").Replace("'""")  
  187.                 End If 
  188.  
  189.                 Return Value  
  190.             End Get 
  191.         End Property 
  192.  
  193.         ''' <summary>获取附件名称</summary>  
  194.         Public ReadOnly Property MIME() As String 
  195.             Get 
  196.                 Return oHttp.ResponseHeaders(Net.HttpResponseHeader.ContentType)  
  197.             End Get 
  198.         End Property 
  199.  
  200.  
  201.         ''' <summary>设置需要上传的表单内容</summary>  
  202.         Public Overloads Property PostString() As String 
  203.             Get 
  204.                 Return xPostString  
  205.             End Get 
  206.             Set(ByVal value As String)  
  207.                 xPostString = value  
  208.             End Set 
  209.         End Property 
  210.  
  211.  
  212.         ''' <summary>设置需要上传的表单内容</summary>  
  213.         Public Overloads WriteOnly Property PostString(ByVal Key As StringAs String 
  214.             Set(ByVal value As String)  
  215.                 If Not String.IsNullOrEmpty(Key) And Not String.IsNullOrEmpty(value) Then 
  216.                     If xCharset.Length < 3 Then 
  217.                         value = Web.HttpUtility.UrlEncode(value, Text.Encoding.GetEncoding("UTF-8"))  
  218.                     Else 
  219.                         value = Web.HttpUtility.UrlEncode(value, Text.Encoding.GetEncoding(xCharset))  
  220.                     End If 
  221.                     xPostString &= "&" & Key & "=" & value  
  222.                 End If 
  223.                 If xPostString.StartsWith("&"Then xPostString = xPostString.Substring(1)  
  224.             End Set 
  225.         End Property 
  226.  
  227.         '-------------------------------------------------------------------------------  
  228.  
  229.         ''' <summary>获取网页源码</summary>  
  230.         Public Overloads Function Html() As String 
  231.             Html = "" 
  232.             If xUrl IsNot Nothing Then 
  233.                 Try 
  234.                     oHttp.Headers.Add(Net.HttpRequestHeader.UserAgent, xUserAgent)  
  235.  
  236.                     '默认使用 UTF-8 编码  
  237.                     Dim retByte As Byte()  
  238.                     If xPostString.Length > 0 Then 
  239.                         oHttp.Headers.Add(Net.HttpRequestHeader.ContentType, "application/x-www-form-urlencoded")  
  240.                         retByte = oHttp.UploadData(xUrl, "POST", Text.Encoding.Default.GetBytes(xPostString))  
  241.                     Else 
  242.                         retByte = oHttp.DownloadData(xUrl)  
  243.                     End If 
  244.  
  245.                     Dim contentType As String = oHttp.ResponseHeaders("Content-Type").ToLower  
  246.  
  247.                     ' 必须返回文本格式的内容才获取实际内容  
  248.                     If contentType.Contains("text"Or contentType.Contains("html"Or contentType.Contains("xml"Then 
  249.                         If xCharset.Length < 1 Then 
  250.                             '1. BOM(Byte Order Mark) 提取编码  
  251.                             If retByte(0) > &HEE Then 
  252.                                 If retByte(0) = &HEF And retByte(1) = &HBB And retByte(2) = &HBF Then xCharset = "UTF-8" 
  253.                                 If retByte(0) = &HFE And retByte(1) = &HFF Then xCharset = "Big-Endian" 
  254.                                 If retByte(0) = &HFF And retByte(1) = &HFE Then xCharset = "Unicode" 
  255.                             End If 
  256.  
  257.                             If xCharset.Length < 1 Then 
  258.                                 '2. Header 提取编码  
  259.                                 '   Content-Type: text/html; charset=UTF-8  
  260.                                 '   正则表达式:charset\b\s*=\s*(?<charset>[^""]*)  
  261.                                 If contentType.Contains("charset="AndAlso Text.RegularExpressions.Regex.IsMatch(contentType, "charset\b\s*=\s*(?<charset>[^""]*)"Then xCharset = Text.RegularExpressions.Regex.Match(contentType, "charset\b\s*=\s*(?<charset>[^""]*)").Groups("charset").Value  
  262.                             End If 
  263.  
  264.                             If xCharset.Length < 1 Then 
  265.                                 '3. HTML 代码中提取  
  266.                                 '   <meta http-equiv=content-type content="text/html; charset=GB2312">  
  267.                                 '   正则表达式:(<meta[^>]*charset=(?<charset>[^>'""]*)[\s\S]*?>)|(xml[^>]+encoding=(""|')*(?<charset>[^>'""]*)[\s\S]*?>)  
  268.                                 Dim Match As Text.RegularExpressions.Match = Text.RegularExpressions.Regex.Match(Text.Encoding.Default.GetString(retByte), "(<meta[^>]*charset=(?<charset>[^>'""]*)[\s\S]*?>)|(xml[^>]+encoding=(""|')*(?<charset>[^>'""]*)[\s\S]*?>)", Text.RegularExpressions.RegexOptions.IgnoreCase)  
  269.                                 If Match.Length > 0 Then xCharset = IIf((Match.Captures.Count <> 0), Match.Result("${charset}"), "")  
  270.                             End If 
  271.                         End If 
  272.  
  273.                         If xCharset.Length > 1 Then 
  274.                             Html = Text.Encoding.GetEncoding(xCharset).GetString(retByte)  
  275.                         Else 
  276.                             Html = Text.Encoding.Default.GetString(retByte)  
  277.                         End If 
  278.                     End If 
  279.                 Catch e As Exception  
  280.                 End Try 
  281.             End If 
  282.         End Function 
  283.  
  284.         ''' <summary>获取网页源码</summary>  
  285.         ''' <param name="UrlAddress">要获取的网址</param>  
  286.         Public Overloads Function Html(ByVal UrlAddress As StringAs String 
  287.             Url = UrlAddress  
  288.             Return Me.Html  
  289.         End Function 
  290.  
  291.         ''' <summary>获取网页源码</summary>  
  292.         ''' <param name="UrlAddress">要获取的网址</param>  
  293.         ''' <param name="PageCharset">访问页面的语言编码</param>  
  294.         Public Overloads Function Html(ByVal UrlAddress As StringByVal PageCharset As StringAs String 
  295.             Charset = PageCharset  
  296.             Url = UrlAddress  
  297.             Return Me.Html  
  298.         End Function 
  299.  
  300.  
  301.         '-------------------------------------------------------------------------------  
  302.  
  303.         ''' <summary>获取网页源码</summary>  
  304.         Public Overloads Function Stream() As IO.Stream  
  305.             If xUrl IsNot Nothing Then 
  306.                 Try 
  307.                     oHttp.Headers.Add(Net.HttpRequestHeader.UserAgent, xUserAgent)  
  308.                     Return oHttp.OpenRead(xUrl)  
  309.                 Catch e As Exception  
  310.                 End Try 
  311.             End If 
  312.  
  313.             Return Nothing 
  314.         End Function 
  315.  
  316.         ''' <summary>获取网页源码</summary>  
  317.         Public Overloads Function Stream(ByVal UrlAddress As StringAs IO.Stream  
  318.             Url = UrlAddress  
  319.             Return Me.Stream()  
  320.         End Function 
  321.  
  322.         '-------------------------------------------------------------------------------  
  323.  
  324.         ''' <summary>下载文件</summary>  
  325.         ''' <param name="Overwrite">是否自动创建</param>  
  326.         Public Overloads Function Download(Optional ByVal Overwrite As Boolean = TrueAs Boolean 
  327.             Dim Value As Boolean = False 
  328.  
  329.             If xUrl IsNot Nothing Then 
  330.                 xFileName(1) = xFileName(0)  
  331.                 If xFileName(1).Length < 1 Then xFileName(1) = xUrl.GetHashCode  
  332.                 If xFilePath.Length < 3 Then xFilePath = Files.Unti.Root  
  333.                 If Not xFilePath.EndsWith("\") Then xFilePath &= "\"  
  334.  
  335.                 '检查 OverWrite  
  336.                 If Not Overwrite Then 
  337.                     '检查是否存在文件,存在则不需要下载直接返回 True  
  338.                     If IO.File.Exists(xFilePath & xFileName(1)) Then Value = True 
  339.                 End If 
  340.  
  341.                 If Not Value Then 
  342.                     Try 
  343.                         oHttp.Headers.Add(Net.HttpRequestHeader.UserAgent, xUserAgent)  
  344.  
  345.                         oHttp.DownloadFile(xUrl, xFilePath & xFileName(1))  
  346.  
  347.                         Dim fileExt As String = IO.Path.GetExtension(xFileName(1))  
  348.  
  349.                         '没有扩展名,从下载的数据中获取名称  
  350.                         If String.IsNullOrEmpty(fileExt) Then 
  351.                             If Not String.IsNullOrEmpty(Attachment) Then fileExt = IO.Path.GetExtension(Attachment)  
  352.  
  353.                             '没有扩展名,从服务器返回文件类型获取  
  354.                             If String.IsNullOrEmpty(fileExt) Then 
  355.                                 fileExt = Unti.Mime2Ext(MIME)  
  356.                                 If Not String.IsNullOrEmpty(fileExt) Then 
  357.                                     '换回文件类型组,如:jpg,jpeg...  
  358.                                     fileExt = fileExt.Split(","c)(0)  
  359.                                 End If 
  360.                             End If 
  361.  
  362.                             '没有扩展名,从路径获取  
  363.                             If String.IsNullOrEmpty(fileExt) Then fileExt = IO.Path.GetExtension(xUrl.AbsoluteUri)  
  364.  
  365.                             If Not String.IsNullOrEmpty(fileExt) Then 
  366.                                 '过滤“?、#”  
  367.                                 fileExt = fileExt.Replace("?"" ").Replace("#"" ")  
  368.                                 fileExt = Split(fileExt, " ")(0)  
  369.                             End If 
  370.  
  371.                             If Not String.IsNullOrEmpty(fileExt) Then 
  372.                                 Dim trueFile As String = xFileName(1) & "." & fileExt  
  373.                                 If IO.File.Exists(xFilePath & trueFile) And Not Overwrite Then 
  374.                                     Value = True 
  375.                                     Exit Try 
  376.                                 Else 
  377.                                     '删除旧文件  
  378.                                     IO.File.Delete(xFilePath & trueFile)  
  379.                                 End If 
  380.  
  381.                                 '重命名文件  
  382.                                 If IO.File.Exists(xFilePath & xFileName(1)) Then 
  383.                                     IO.File.Copy(xFilePath & xFileName(1), xFilePath & trueFile)  
  384.                                     IO.File.Delete(xFilePath & xFileName(1))  
  385.                                 End If 
  386.  
  387.                                 xFileName(1) = trueFile  
  388.                             End If 
  389.                         End If 
  390.  
  391.                         Value = True 
  392.                     Catch e As Exception  
  393.                         Value = False 
  394.                     End Try 
  395.                 End If 
  396.             End If 
  397.  
  398.             If Not Value Then xFileName(1) = "" 
  399.  
  400.             Return Value  
  401.         End Function 
  402.  
  403.         ''' <summary>下载文件</summary>  
  404.         ''' <param name="UrlAddress">要操作的网页地址</param>  
  405.         ''' <param name="Overwrite">是否自动创建</param>  
  406.         Public Overloads Function Download(ByVal UrlAddress As StringOptional ByVal Overwrite As Boolean = TrueAs Boolean 
  407.             Url = UrlAddress  
  408.             Return Me.Download(Overwrite)  
  409.         End Function 
  410.  
  411.         ''' <summary>下载文件</summary>  
  412.         ''' <param name="UrlAddress">要操作的网页地址</param>  
  413.         ''' <param name="SaveFilePath">下载后文件保存路径</param>  
  414.         ''' <param name="Overwrite">是否自动创建</param>  
  415.         Public Overloads Function Download(ByVal UrlAddress As StringByVal SaveFilePath As StringByVal SaveFileName As StringOptional ByVal Overwrite As Boolean = TrueAs Boolean 
  416.             Url = UrlAddress  
  417.             FilePath = SaveFilePath  
  418.             FileName = SaveFileName  
  419.             Download = Me.Download(Overwrite)  
  420.         End Function 
  421.     End Class 
  422. End Namespace 

 

· 本文由 木炭 发布在《激情燃烧的木炭》 上,原文地址为:http://www.woodcoal.cn/project/dll-base/200938-1770-553.html(转载请保留本信息、全文内容和链接)

发表评论

已经有 0 位朋友发表了对《WoodCoal.Base.Http.Client》的看法
 
登录名:  密码:   登录  注册
评论: 
User:
Contact:
验证码:  
  [Ctrl+Enter]

快捷导航

推荐文章