http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 4756|回复: 6

[求助] 我不得不说,要是加上upload file 和multipart/form-data 就好了

[复制链接]
发表于 2013-1-16 14:23:37 | 显示全部楼层 |阅读模式
[code=vb]Imports System.Collections.Generic
Imports System.Text
Imports System.Net
Imports System.IO
Imports System.Threading

Namespace jayleke
    Public Class HttpHelper
#Region "私有变量"
        Private Shared cc As New CookieContainer()
        Private Shared contentType As String = "application/x-www-form-urlencoded"
        Private Shared accept As String = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*"
        Private Shared userAgent As String = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)"
        Private Shared m_encoding As Encoding = Encoding.GetEncoding("utf-8")
        Private Shared delay As Integer = 3000
        '延迟访问防止连续访问被发现  
        Private Shared m_maxTry As Integer = 300
        Private Shared currentTry As Integer = 0
#End Region

#Region "属性"
        ''' <summary></summary>  
        ''' Cookie容器  
        '''   
        Public Shared ReadOnly Property CookieContainer() As CookieContainer
            Get
                Return cc
            End Get
        End Property

        ''' <summary></summary>  
        ''' 获取网页源码时使用的编码  
        '''   
        ''' <value></value>  
        Public Shared Property Encoding() As Encoding
            Get
                Return m_encoding
            End Get
            Set(value As Encoding)
                m_encoding = value
            End Set
        End Property

        Public Shared Property NetworkDelay() As Integer
            Get
                Dim r As New Random()
                Return (r.[Next](delay \ 1000, (delay \ 1000) * 2)) * 1000
            End Get
            Set(value As Integer)
                delay = value
            End Set
        End Property

        Public Shared Property MaxTry() As Integer
            Get
                Return m_maxTry
            End Get
            Set(value As Integer)
                m_maxTry = value
            End Set
        End Property
#End Region

#Region "公共方法"

        Public Shared Function GetHtml(url As String, postData As String, isPost As Boolean, cookieContainer As CookieContainer) As String

            If String.IsNullOrEmpty(postData) Then Return GetHtml(url, cookieContainer)
            Thread.Sleep(NetworkDelay)
            currentTry += 1

            Dim httpWebRequest__1 As HttpWebRequest = Nothing
            Dim httpWebResponse As HttpWebResponse = Nothing
            Try
                Dim byteRequest As Byte() = Encoding.[Default].GetBytes(postData)
                httpWebRequest__1 = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
                httpWebRequest__1.CookieContainer = cookieContainer
                httpWebRequest__1.ContentType = contentType
                httpWebRequest__1.ServicePoint.ConnectionLimit = m_maxTry
                httpWebRequest__1.Referer = url
                httpWebRequest__1.Accept = accept
                httpWebRequest__1.UserAgent = userAgent
                httpWebRequest__1.Method = If(isPost, "POST", "GET")
                httpWebRequest__1.ContentLength = byteRequest.Length
                Dim stream As Stream = httpWebRequest__1.GetRequestStream()
                stream.Write(byteRequest, 0, byteRequest.Length)
                stream.Close()
                httpWebResponse = DirectCast(httpWebRequest__1.GetResponse(), HttpWebResponse)
                Dim responseStream As Stream = httpWebResponse.GetResponseStream()
                Dim streamReader As New StreamReader(responseStream, m_encoding)
                Dim html As String = streamReader.ReadToEnd()
                streamReader.Close()
                responseStream.Close()
                currentTry = 0
                httpWebRequest__1.Abort()
                httpWebResponse.Close()
                Return html
            Catch e As Exception
                Console.ForegroundColor = ConsoleColor.Red
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ") & e.Message)
                Console.ForegroundColor = ConsoleColor.White
                If currentTry <= m_maxTry Then GetHtml(url, postData, isPost, cookieContainer)
                currentTry -= 1
                If httpWebRequest__1 IsNot Nothing Then httpWebRequest__1.Abort()
                If httpWebResponse IsNot Nothing Then httpWebResponse.Close()
                Return String.Empty
            End Try

        End Function


        Public Shared Function GetHtml(url As String, cookieContainer As CookieContainer) As String
            Thread.Sleep(NetworkDelay)

            currentTry += 1
            Dim httpWebRequest__1 As HttpWebRequest = Nothing
            Dim httpWebResponse As HttpWebResponse = Nothing
            Try

                httpWebRequest__1 = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
                httpWebRequest__1.CookieContainer = cookieContainer
                httpWebRequest__1.ContentType = contentType
                httpWebRequest__1.ServicePoint.ConnectionLimit = m_maxTry
                httpWebRequest__1.Referer = url
                httpWebRequest__1.Accept = accept
                httpWebRequest__1.UserAgent = userAgent
                httpWebRequest__1.Method = "GET"

                httpWebResponse = DirectCast(httpWebRequest__1.GetResponse(), HttpWebResponse)
                Dim responseStream As Stream = httpWebResponse.GetResponseStream()
                Dim streamReader As New StreamReader(responseStream, m_encoding)
                Dim html As String = streamReader.ReadToEnd()
                streamReader.Close()
                responseStream.Close()

                currentTry -= 1

                httpWebRequest__1.Abort()
                httpWebResponse.Close()

                Return html
            Catch e As Exception
                Console.ForegroundColor = ConsoleColor.Red
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ") & e.Message)
                Console.ForegroundColor = ConsoleColor.White

                If currentTry <= m_maxTry Then
                    GetHtml(url, cookieContainer)
                End If

                currentTry -= 1

                If httpWebRequest__1 IsNot Nothing Then
                    httpWebRequest__1.Abort()
                End If
                If httpWebResponse IsNot Nothing Then
                    httpWebResponse.Close()
                End If
                Return String.Empty
            End Try
        End Function

        Public Shared Function GetHtml(url As String) As String
            Return GetHtml(url, cc)
        End Function

        Public Shared Function GetHtml(ByVal url As String, ByRef postPara As System.Collections.Hashtable, ByVal isPost As Boolean) As String

            Return GetHtml(url, ColToStr(postPara), isPost, cc)

        End Function

        Public Shared Function GetHtml(url As String, postData As String, isPost As Boolean) As String
            Return GetHtml(url, postData, isPost, cc)
        End Function

        Public Shared Function GetStream(url As String) As Stream
            Return GetStream(url, cc)
        End Function

        Public Shared Function GetStream(url As String, cookieContainer As CookieContainer) As Stream
            'Thread.Sleep(delay);  

            currentTry += 1
            Dim httpWebRequest__1 As HttpWebRequest = Nothing
            Dim httpWebResponse As HttpWebResponse = Nothing

            Try

                httpWebRequest__1 = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
                httpWebRequest__1.CookieContainer = cookieContainer
                httpWebRequest__1.ContentType = contentType
                httpWebRequest__1.ServicePoint.ConnectionLimit = m_maxTry
                httpWebRequest__1.Referer = url
                httpWebRequest__1.Accept = accept
                httpWebRequest__1.UserAgent = userAgent
                httpWebRequest__1.Method = "GET"

                httpWebResponse = DirectCast(httpWebRequest__1.GetResponse(), HttpWebResponse)
                Dim responseStream As Stream = httpWebResponse.GetResponseStream()
                currentTry -= 1

                'httpWebRequest.Abort();  
                'httpWebResponse.Close();  

                Return responseStream
            Catch e As Exception
                Console.ForegroundColor = ConsoleColor.Red
                Console.WriteLine(DateTime.Now.ToString("HH:mm:ss ") & e.Message)
                Console.ForegroundColor = ConsoleColor.White

                If currentTry <= m_maxTry Then
                    GetHtml(url, cookieContainer)
                End If

                currentTry -= 1

                If httpWebRequest__1 IsNot Nothing Then
                    httpWebRequest__1.Abort()
                End If
                If httpWebResponse IsNot Nothing Then
                    httpWebResponse.Close()
                End If
                Return Nothing
            End Try
        End Function[/code]


1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
 楼主| 发表于 2013-1-16 14:26:47 | 显示全部楼层
[code=vb]Public Shared Function UpFile(GetUrl As String, PutUrl As String) As String
            Return UpFile(GetUrl, PutUrl, cc)
        End Function

        Public Shared Function ColToStr(ByRef ht As System.Collections.Hashtable) As String

            Dim str As String = Nothing, para As DictionaryEntry

            For Each para In ht

                str &= System.Web.HttpUtility.UrlEncode(CType(para.Key, String), m_encoding)
                str &= "="
                str &= System.Web.HttpUtility.UrlEncode(CType(para.Value, String), m_encoding)
                str &= "&"

            Next

            Return str.Substring(0, str.Length - 1)

        End Function

#End Region


        Public Shared Function UpFile(GetUrl As String, PutUrl As String, cookieContainer As CookieContainer) As String

            Dim Image As Stream = HttpHelper.GetStream(GetUrl)
            Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
            Dim boundarybytes As Byte() = System.Text.Encoding.ASCII.GetBytes(vbCr & vbLf & "--" & boundary & vbCr & vbLf)
            Thread.Sleep(NetworkDelay)
            currentTry += 1
            Dim httpWebRequest__1 As HttpWebRequest = Nothing
            Dim httpWebResponse As HttpWebResponse = Nothing
            Try
                httpWebRequest__1 = DirectCast(HttpWebRequest.Create(PutUrl), HttpWebRequest)
                httpWebRequest__1.CookieContainer = cookieContainer
                httpWebRequest__1.ContentType = "multipart/form-data; boundary=" & boundary
                httpWebRequest__1.KeepAlive = True
                httpWebRequest__1.ServicePoint.ConnectionLimit = m_maxTry
                httpWebRequest__1.Accept = accept
                httpWebRequest__1.UserAgent = userAgent
                httpWebRequest__1.Method = "POST"
                Dim stream As Stream = httpWebRequest__1.GetRequestStream()
                stream.Write(boundarybytes, 0, boundarybytes.Length)
                Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""" & vbCr & vbLf & "Content-Type: {2}" & vbCr & vbLf & vbCr & vbLf
                Dim header As String = String.Format(headerTemplate, "imageFile", Path.GetFileName(GetUrl), "image/jpeg")
                Dim headerbytes As Byte() = System.Text.Encoding.UTF8.GetBytes(header)
                stream.Write(headerbytes, 0, headerbytes.Length)

                HttpContext.Current.Response.Write(IO.Path.GetFileName(GetUrl))
                HttpContext.Current.Response.Write(GetContentType(IO.Path.GetFileName(GetUrl)))


                Dim buffer As Byte() = New Byte(4095) {}
                Dim byteSeq As Integer = Image.Read(buffer, 0, 4096)

                Do While byteSeq > 0
                    stream.Write(buffer, 0, byteSeq)
                    byteSeq = Image.Read(buffer, 0, 4096)
                Loop


                Dim trailer As Byte() = System.Text.Encoding.ASCII.GetBytes(vbCr & vbLf & "--" & boundary & "--" & vbCr & vbLf)
                stream.Write(trailer, 0, trailer.Length)





                stream.Close()
                httpWebResponse = DirectCast(httpWebRequest__1.GetResponse(), HttpWebResponse)
                Dim responseStream As Stream = httpWebResponse.GetResponseStream()
                Dim streamReader As New StreamReader(responseStream, m_encoding)
                Dim html As String = streamReader.ReadToEnd()
                streamReader.Close()
                responseStream.Close()
                currentTry = 0
                httpWebRequest__1.Abort()
                httpWebResponse.Close()
                Return html
            Catch e As Exception
      
                If currentTry <= m_maxTry Then UpFile(GetUrl, PutUrl, cookieContainer)
                currentTry -= 1
                If httpWebRequest__1 IsNot Nothing Then httpWebRequest__1.Abort()
                If httpWebResponse IsNot Nothing Then httpWebResponse.Close()
                Return String.Empty
            End Try

        End Function


   


        Public Shared Function GetContentType(filename As String) As String
            Dim fileExtKey As Microsoft.Win32.RegistryKey = Nothing


            Dim contentType As String = "application/stream"
            Try
                fileExtKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(Path.GetExtension(filename))
                contentType = fileExtKey.GetValue("Content Type", contentType).ToString()
            Finally
                If fileExtKey IsNot Nothing Then
                    fileExtKey.Close()
                End If
            End Try
            Return contentType
        End Function





    End Class
End Namespace[/code]
 楼主| 发表于 2013-1-16 14:30:19 | 显示全部楼层
form-data~




[code=vb]    '''<summary>  
        '''分析文本域,添加到请求流  
        '''</summary>  
        '''<param name="textField">文本域</param>  
        Private Sub WriteTextField(textField As String)
            Dim strArr As String() = RE.Split(textField, "&")
            textField = ""
            For Each var As String In strArr
                Dim M As Match = RE.Match(var, "([^=]+)=(.+)")
                textField += "--" & BOUNDARY & vbCr & vbLf
                textField += "Content-Disposition: form-data; name=""" & M.Groups(1).Value & """" & vbCr & vbLf & vbCr & vbLf & M.Groups(2).Value & vbCr & vbLf
            Next
            Dim buffer As Byte() = m_encoding.GetBytes(textField)
            postStream.Write(buffer, 0, buffer.Length)
        End Sub

        '''<summary>  
        '''分析文件域,添加到请求流  
        '''</summary>  
        '''<param name="fileField">文件域</param>  
        Private Sub WriteFileField(fileField As String)
            Dim filePath As String = ""
            Dim count As Integer = 0
            Dim strArr As String() = RE.Split(fileField, "&")
            For Each var As String In strArr
                Dim M As Match = RE.Match(var, "([^=]+)=(.+)")
                filePath = M.Groups(2).Value
                fileField = "--" & BOUNDARY & vbCr & vbLf
                fileField += "Content-Disposition: form-data; name=""" & M.Groups(1).Value & """; filename=""" & Path.GetFileName(filePath) & """" & vbCr & vbLf
                fileField += "Content-Type: image/jpeg" & vbCr & vbLf & vbCr & vbLf

                Dim buffer As Byte() = m_encoding.GetBytes(fileField)
                postStream.Write(buffer, 0, buffer.Length)

                '添加文件数据  
                Dim fs As New FileStream(filePath, FileMode.Open, FileAccess.Read)
                buffer = New Byte(49999) {}

                Do
                    count = fs.Read(buffer, 0, buffer.Length)

                    postStream.Write(buffer, 0, count)
                Loop While count > 0

                fs.Close()
                fs.Dispose()
                fs = Nothing

                buffer = m_encoding.GetBytes(vbCr & vbLf)
                postStream.Write(buffer, 0, buffer.Length)
            Next
        End Sub[/code]
发表于 2013-1-16 14:52:04 | 显示全部楼层
这个我已开始整理,请期待下一个版本,另个感谢你的分享
发表于 2013-4-22 09:12:50 | 显示全部楼层
哪个呦,发这么好的帖子,顶你
发表于 2013-8-20 13:48:25 | 显示全部楼层
站长苏飞 发表于 2013-1-16 14:52
这个我已开始整理,请期待下一个版本,另个感谢你的分享

现在加进去了么
发表于 2013-8-28 22:11:17 | 显示全部楼层
最近也遇到了multipart/form-data的问题。期待解决。
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-5-4 13:19

© 2014-2021

快速回复 返回顶部 返回列表