Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports Microsoft.VisualBasic
- Imports Microsoft.VisualBasic.CompilerServices
- Imports System
- Imports System.Collections.Generic
- Imports System.Collections.Specialized
- Imports System.Diagnostics
- Imports System.Drawing
- Imports System.Drawing.Imaging
- Imports System.IO
- Imports System.IO.Compression
- Imports System.Net
- Imports System.Net.Configuration
- Imports System.Net.Security
- Imports System.Reflection
- Imports System.Runtime.CompilerServices
- Imports System.Runtime.InteropServices
- Imports System.Security.Cryptography.X509Certificates
- Imports System.Text
- Imports System.Text.RegularExpressions
- Namespace Utility
- Public Class Connection
- Implements IDisposable
- Public Property UsedCookies As Boolean
- Shared Sub New()
- Dim dictionary As New Dictionary(Of String, String)
- dictionary.Add("ai", "application/postscript")
- dictionary.Add("aif", "audio/x-aiff")
- dictionary.Add("aifc", "audio/x-aiff")
- dictionary.Add("aiff", "audio/x-aiff")
- dictionary.Add("asc", "text/plain")
- dictionary.Add("atom", "application/atom+xml")
- dictionary.Add("au", "audio/basic")
- dictionary.Add("avi", "video/x-msvideo")
- dictionary.Add("bcpio", "application/x-bcpio")
- dictionary.Add("bin", "application/octet-stream")
- dictionary.Add("bmp", "image/bmp")
- dictionary.Add("cdf", "application/x-netcdf")
- dictionary.Add("cgm", "image/cgm")
- dictionary.Add("class", "application/octet-stream")
- dictionary.Add("cpio", "application/x-cpio")
- dictionary.Add("cpt", "application/mac-compactpro")
- dictionary.Add("csh", "application/x-csh")
- dictionary.Add("css", "text/css")
- dictionary.Add("dcr", "application/x-director")
- dictionary.Add("dif", "video/x-dv")
- dictionary.Add("dir", "application/x-director")
- dictionary.Add("djv", "image/vnd.djvu")
- dictionary.Add("djvu", "image/vnd.djvu")
- dictionary.Add("dll", "application/octet-stream")
- dictionary.Add("dmg", "application/octet-stream")
- dictionary.Add("dms", "application/octet-stream")
- dictionary.Add("doc", "application/msword")
- dictionary.Add("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
- dictionary.Add("dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template")
- dictionary.Add("docm", "application/vnd.ms-word.document.macroEnabled.12")
- dictionary.Add("dotm", "application/vnd.ms-word.template.macroEnabled.12")
- dictionary.Add("dtd", "application/xml-dtd")
- dictionary.Add("dv", "video/x-dv")
- dictionary.Add("dvi", "application/x-dvi")
- dictionary.Add("dxr", "application/x-director")
- dictionary.Add("eps", "application/postscript")
- dictionary.Add("etx", "text/x-setext")
- dictionary.Add("exe", "application/octet-stream")
- dictionary.Add("ez", "application/andrew-inset")
- dictionary.Add("gif", "image/gif")
- dictionary.Add("gram", "application/srgs")
- dictionary.Add("grxml", "application/srgs+xml")
- dictionary.Add("gtar", "application/x-gtar")
- dictionary.Add("hdf", "application/x-hdf")
- dictionary.Add("hqx", "application/mac-binhex40")
- dictionary.Add("htm", "text/html")
- dictionary.Add("html", "text/html")
- dictionary.Add("ice", "x-conference/x-cooltalk")
- dictionary.Add("ico", "image/x-icon")
- dictionary.Add("ics", "text/calendar")
- dictionary.Add("ief", "image/ief")
- dictionary.Add("ifb", "text/calendar")
- dictionary.Add("iges", "model/iges")
- dictionary.Add("igs", "model/iges")
- dictionary.Add("jnlp", "application/x-java-jnlp-file")
- dictionary.Add("jp2", "image/jp2")
- dictionary.Add("jpe", "image/jpeg")
- dictionary.Add("jpeg", "image/jpeg")
- dictionary.Add("jpg", "image/jpeg")
- dictionary.Add("js", "application/x-javascript")
- dictionary.Add("kar", "audio/midi")
- dictionary.Add("latex", "application/x-latex")
- dictionary.Add("lha", "application/octet-stream")
- dictionary.Add("lzh", "application/octet-stream")
- dictionary.Add("m3u", "audio/x-mpegurl")
- dictionary.Add("m4a", "audio/mp4a-latm")
- dictionary.Add("m4b", "audio/mp4a-latm")
- dictionary.Add("m4p", "audio/mp4a-latm")
- dictionary.Add("m4u", "video/vnd.mpegurl")
- dictionary.Add("m4v", "video/x-m4v")
- dictionary.Add("mac", "image/x-macpaint")
- dictionary.Add("man", "application/x-troff-man")
- dictionary.Add("mathml", "application/mathml+xml")
- dictionary.Add("me", "application/x-troff-me")
- dictionary.Add("mesh", "model/mesh")
- dictionary.Add("mid", "audio/midi")
- dictionary.Add("midi", "audio/midi")
- dictionary.Add("mif", "application/vnd.mif")
- dictionary.Add("mov", "video/quicktime")
- dictionary.Add("movie", "video/x-sgi-movie")
- dictionary.Add("mp2", "audio/mpeg")
- dictionary.Add("mp3", "audio/mpeg")
- dictionary.Add("mp4", "video/mp4")
- dictionary.Add("mpe", "video/mpeg")
- dictionary.Add("mpeg", "video/mpeg")
- dictionary.Add("mpg", "video/mpeg")
- dictionary.Add("mpga", "audio/mpeg")
- dictionary.Add("ms", "application/x-troff-ms")
- dictionary.Add("msh", "model/mesh")
- dictionary.Add("mxu", "video/vnd.mpegurl")
- dictionary.Add("nc", "application/x-netcdf")
- dictionary.Add("oda", "application/oda")
- dictionary.Add("ogg", "application/ogg")
- dictionary.Add("pbm", "image/x-portable-bitmap")
- dictionary.Add("pct", "image/pict")
- dictionary.Add("pdb", "chemical/x-pdb")
- dictionary.Add("pdf", "application/pdf")
- dictionary.Add("pgm", "image/x-portable-graymap")
- dictionary.Add("pgn", "application/x-chess-pgn")
- dictionary.Add("pic", "image/pict")
- dictionary.Add("pict", "image/pict")
- dictionary.Add("png", "image/png")
- dictionary.Add("pnm", "image/x-portable-anymap")
- dictionary.Add("pnt", "image/x-macpaint")
- dictionary.Add("pntg", "image/x-macpaint")
- dictionary.Add("ppm", "image/x-portable-pixmap")
- dictionary.Add("ppt", "application/vnd.ms-powerpoint")
- dictionary.Add("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation")
- dictionary.Add("potx", "application/vnd.openxmlformats-officedocument.presentationml.template")
- dictionary.Add("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow")
- dictionary.Add("ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12")
- dictionary.Add("pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12")
- dictionary.Add("potm", "application/vnd.ms-powerpoint.template.macroEnabled.12")
- dictionary.Add("ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12")
- dictionary.Add("ps", "application/postscript")
- dictionary.Add("qt", "video/quicktime")
- dictionary.Add("qti", "image/x-quicktime")
- dictionary.Add("qtif", "image/x-quicktime")
- dictionary.Add("ra", "audio/x-pn-realaudio")
- dictionary.Add("ram", "audio/x-pn-realaudio")
- dictionary.Add("ras", "image/x-cmu-raster")
- dictionary.Add("rdf", "application/rdf+xml")
- dictionary.Add("rgb", "image/x-rgb")
- dictionary.Add("rm", "application/vnd.rn-realmedia")
- dictionary.Add("roff", "application/x-troff")
- dictionary.Add("rtf", "text/rtf")
- dictionary.Add("rtx", "text/richtext")
- dictionary.Add("sgm", "text/sgml")
- dictionary.Add("sgml", "text/sgml")
- dictionary.Add("sh", "application/x-sh")
- dictionary.Add("shar", "application/x-shar")
- dictionary.Add("silo", "model/mesh")
- dictionary.Add("sit", "application/x-stuffit")
- dictionary.Add("skd", "application/x-koan")
- dictionary.Add("skm", "application/x-koan")
- dictionary.Add("skp", "application/x-koan")
- dictionary.Add("skt", "application/x-koan")
- dictionary.Add("smi", "application/smil")
- dictionary.Add("smil", "application/smil")
- dictionary.Add("snd", "audio/basic")
- dictionary.Add("so", "application/octet-stream")
- dictionary.Add("spl", "application/x-futuresplash")
- dictionary.Add("src", "application/x-wais-source")
- dictionary.Add("sv4cpio", "application/x-sv4cpio")
- dictionary.Add("sv4crc", "application/x-sv4crc")
- dictionary.Add("svg", "image/svg+xml")
- dictionary.Add("swf", "application/x-shockwave-flash")
- dictionary.Add("t", "application/x-troff")
- dictionary.Add("tar", "application/x-tar")
- dictionary.Add("tcl", "application/x-tcl")
- dictionary.Add("tex", "application/x-tex")
- dictionary.Add("texi", "application/x-texinfo")
- dictionary.Add("texinfo", "application/x-texinfo")
- dictionary.Add("tif", "image/tiff")
- dictionary.Add("tiff", "image/tiff")
- dictionary.Add("tr", "application/x-troff")
- dictionary.Add("tsv", "text/tab-separated-values")
- dictionary.Add("txt", "text/plain")
- dictionary.Add("ustar", "application/x-ustar")
- dictionary.Add("vcd", "application/x-cdlink")
- dictionary.Add("vrml", "model/vrml")
- dictionary.Add("vxml", "application/voicexml+xml")
- dictionary.Add("wav", "audio/x-wav")
- dictionary.Add("wbmp", "image/vnd.wap.wbmp")
- dictionary.Add("wbmxl", "application/vnd.wap.wbxml")
- dictionary.Add("wml", "text/vnd.wap.wml")
- dictionary.Add("wmlc", "application/vnd.wap.wmlc")
- dictionary.Add("wmls", "text/vnd.wap.wmlscript")
- dictionary.Add("wmlsc", "application/vnd.wap.wmlscriptc")
- dictionary.Add("wrl", "model/vrml")
- dictionary.Add("xbm", "image/x-xbitmap")
- dictionary.Add("xht", "application/xhtml+xml")
- dictionary.Add("xhtml", "application/xhtml+xml")
- dictionary.Add("xls", "application/vnd.ms-excel")
- dictionary.Add("xml", "application/xml")
- dictionary.Add("xpm", "image/x-xpixmap")
- dictionary.Add("xsl", "application/xml")
- dictionary.Add("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- dictionary.Add("xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template")
- dictionary.Add("xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12")
- dictionary.Add("xltm", "application/vnd.ms-excel.template.macroEnabled.12")
- dictionary.Add("xlam", "application/vnd.ms-excel.addin.macroEnabled.12")
- dictionary.Add("xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12")
- dictionary.Add("xslt", "application/xslt+xml")
- dictionary.Add("xul", "application/vnd.mozilla.xul+xml")
- dictionary.Add("xwd", "image/x-xwindowdump")
- dictionary.Add("xyz", "chemical/x-xyz")
- dictionary.Add("zip", "application/zip")
- Connection.MIMETypes = dictionary
- End Sub
- Public Sub New()
- Me.SetUnsafeHeaderParsing(True)
- ServicePointManager.DefaultConnectionLimit = 500
- ServicePointManager.Expect100Continue = Me.AllowExpect100
- ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf Me.AcceptAllCertifications)
- ServicePointManager.UseNagleAlgorithm = False
- ServicePointManager.SecurityProtocol = (SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3)
- Me.SessionCookies = New List(Of HttpCookie)
- End Sub
- Private Function AcceptAllCertifications(ByVal sender As Object, ByVal certification As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
- Return True
- End Function
- Public Sub AddCookie(ByVal c As HttpCookie)
- Me.SessionCookies.Add(c)
- End Sub
- Public Sub AddCookie(ByVal c As HttpCookie())
- Me.SessionCookies.AddRange(c)
- End Sub
- Public Shared Function Base36Decode(ByVal Data As String) As Long
- Dim bytes As Byte() = Convert.FromBase64String(Data)
- Return Conversions.ToLong(Encoding.UTF8.GetString(bytes))
- End Function
- Public Shared Function Base36Encode(ByVal Data As Long) As String
- Dim chArray As Char() = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray
- Dim stack As New Stack(Of Char)
- Do While Not Data.Equals(CLng(0))
- stack.Push(chArray(CInt(Convert.ToInt64(CLng((Data Mod &H24))))))
- Data = Convert.ToInt64(CDbl((CDbl(Data) / 36)))
- Loop
- Return New String(stack.ToArray)
- End Function
- Public Shared Function Base64ToImage(ByVal [Text] As String) As Image
- Dim image2 As Image = Nothing
- Try
- Dim buffer As Byte() = Convert.FromBase64String([Text])
- Using stream As MemoryStream = New MemoryStream(buffer, 0, buffer.Length)
- stream.Write(buffer, 0, buffer.Length)
- image2 = Image.FromStream(stream, True)
- End Using
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Debug.Print(ex.ToString)
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return image2
- End Function
- Public Sub ClearCookies()
- Me.SessionCookies.Clear()
- End Sub
- Public Shared Function CountOccurance(ByVal Data As String, ByVal Search As String, Optional ByVal CaseSensitive As Boolean = False) As Integer
- Return Convert.ToInt32(CDbl((CDbl(Convert.ToInt32(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(Interaction.IIf(CaseSensitive, (Data.Length - Data.Replace(Search, "").Length), (Data.Length - Data.ToLower.Replace(Search.ToLower, "").Length))))))) / CDbl(Search.Length))))
- End Function
- Public Sub Dispose() Implements IDisposable.Dispose
- Me.Dispose(True)
- GC.SuppressFinalize(Me)
- End Sub
- Protected Overridable Sub Dispose(ByVal disposing As Boolean)
- If (Not Me.disposedValue AndAlso disposing) Then
- Me.RedirectBlacklist.Clear()
- Me.SessionCookies.Clear()
- End If
- Me.disposedValue = True
- End Sub
- Public Function DownloadFile(ByVal Path As String, ByVal Url As String) As HttpResponse
- Dim response2 As New HttpResponse
- Dim expression As Exception = Nothing
- Dim client As New WebClient
- Try
- Dim client2 As WebClient = client
- If Not String.IsNullOrEmpty(Me.Referer) Then
- client2.Headers.Add(HttpRequestHeader.Referer, Me.Referer)
- End If
- If Me.SendCookies Then
- Dim str As String = Interaction.IIf(Me.UseCustomCookies, Me.GetCookies(Me.CustomCookies), Me.GetCookies(Url)).ToString
- If Not String.IsNullOrEmpty(str) Then
- client2.Headers.Add(HttpRequestHeader.Cookie, str)
- End If
- End If
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- client2.Proxy = New WebProxy(Me.Proxy.Server, Me.Proxy.Port)
- If Not String.IsNullOrEmpty(Me.Proxy.UserName) Then
- client2.Proxy.Credentials = New NetworkCredential(Me.Proxy.UserName, Me.Proxy.Password)
- End If
- End If
- client2.DownloadFile(Url, Path)
- client2 = Nothing
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- expression = ex
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- Finally
- client.Dispose()
- If Not Information.IsNothing(expression) Then
- response2.Error = Me.ProcessException(expression)
- End If
- End Try
- Return response2
- End Function
- Public Shared Function EscapeUnicode(ByVal Data As String) As String
- Return Regex.Unescape(Data)
- End Function
- Public Function FindCookie(ByVal Name As String) As HttpCookie
- Dim cookie As HttpCookie
- For Each cookie In Me.SessionCookies
- If (cookie.Name = Name) Then
- Return cookie
- End If
- Next
- Return Nothing
- End Function
- Public Function FindCookie(ByVal Name As String, ByVal Domain As String) As HttpCookie
- Dim cookie As HttpCookie
- For Each cookie In Me.SessionCookies
- If ((cookie.Name = Name) AndAlso (cookie.Domain = Domain)) Then
- Return cookie
- End If
- Next
- Return Nothing
- End Function
- <DllImport("urlmon.dll", CharSet:=CharSet.Auto)>
- Private Shared Function FindMimeFromData(ByVal pBC As UInt32, <MarshalAs(UnmanagedType.LPStr)> ByVal pwzUrl As String, <MarshalAs(UnmanagedType.LPArray)> ByVal pBuffer As Byte(), ByVal cbSize As UInt32, <MarshalAs(UnmanagedType.LPStr)> ByVal pwzMimeProposed As String, ByVal dwMimeFlags As UInt32, ByRef ppwzMimeOut As UInt32, ByVal dwReserverd As UInt32) As UInt32
- End Function
- Public Shared Function FixData(ByVal Data As String) As String
- Return Data.Replace("\u003e", ">").Replace("\u003c", "<").Replace("\u003a", ":").Replace("\u003b", ";").Replace("\u003f", "?").Replace("\u003d", "=").Replace("\u002f", "/").Replace("\u0026", "&").Replace("\u002b", "+").Replace("\u0025", "%").Replace("\u0027", "'").Replace("\u007b", "{").Replace("\u007d", "}").Replace("\u007c", "|").Replace("\u0022", """").Replace("\u0023", "#").Replace("\u0021", "!").Replace("\u0024", "$").Replace("\u0040", "@").Replace("\002f", "/").Replace("\r\n", ChrW(13) & ChrW(10) & ChrW(13) & ChrW(10)).Replace("\n", ChrW(13) & ChrW(10)).Replace("\x3a", ":").Replace("\x2f", "/").Replace("\x3f", "?").Replace("\x3d", "=").Replace("\x26", "&").Replace("\&", "&").Replace("\/\/", "//").Replace("\\", "\").Replace("\""", """").Replace("\/", "/")
- End Function
- Public Shared Function GenerateGuid() As String
- Return Guid.NewGuid.ToString.Replace("-", "")
- End Function
- Public Function GetAllCookies() As List(Of HttpCookie)
- Return Me.SessionCookies
- End Function
- Public Function GetCookies(ByVal Names As String()) As HttpCookie()
- Dim list As New List(Of HttpCookie)
- Dim str As String
- For Each str In Names
- Dim expression As HttpCookie = Me.FindCookie(str)
- If Not Information.IsNothing(expression) Then
- list.Add(expression)
- End If
- Next
- Return list.ToArray
- End Function
- Private Function GetCookies(ByVal Cookies As HttpCookie()) As String
- Dim str2 As String = String.Empty
- If Not Information.IsNothing(Cookies) Then
- Dim cookieArray As HttpCookie() = Cookies
- If (cookieArray.Length = 0) Then
- Return str2
- End If
- Dim cookie As HttpCookie
- For Each cookie In Cookies
- str2 = (str2 & cookie.Name & Interaction.IIf(String.IsNullOrEmpty(cookie.Value), "", ("=" & cookie.Value)).ToString & "; ")
- Next
- If str2.EndsWith("; ") Then
- str2 = str2.Substring(0, (str2.Length - 2))
- End If
- cookieArray = Nothing
- End If
- Return str2
- End Function
- Private Function GetCookies(ByVal RequestUri As String) As String
- Dim str2 As String = String.Empty
- If RequestUri.StartsWith("https://") Then
- RequestUri = ("http://" & RequestUri.Substring((RequestUri.IndexOf("//") + 2)))
- End If
- If Not RequestUri.StartsWith("http") Then
- RequestUri = ("http://" & RequestUri)
- End If
- Dim uri As New Uri(RequestUri)
- If Not Information.IsNothing(Me.SessionCookies) Then
- If (Me.SessionCookies.Count <> 0) Then
- Dim cookie As HttpCookie
- For Each cookie In Me.SessionCookies
- If (cookie.Domain.ToLower.Trim = uri.Host.ToLower.Trim) Then
- str2 = (str2 & cookie.Name & Interaction.IIf(String.IsNullOrEmpty(cookie.Value), "", ("=" & cookie.Value)).ToString & "; ")
- ElseIf (cookie.Domain.StartsWith(".") AndAlso uri.Host.Contains(cookie.Domain)) Then
- str2 = (str2 & cookie.Name & Interaction.IIf(String.IsNullOrEmpty(cookie.Value), "", ("=" & cookie.Value)).ToString & "; ")
- ElseIf (cookie.Domain.StartsWith(".") AndAlso (Connection.CountOccurance(uri.Host, ".", False) = 1)) Then
- str2 = (str2 & cookie.Name & Interaction.IIf(String.IsNullOrEmpty(cookie.Value), "", ("=" & cookie.Value)).ToString & "; ")
- ElseIf cookie.Domain.Contains(uri.Host) Then
- str2 = (str2 & cookie.Name & Interaction.IIf(String.IsNullOrEmpty(cookie.Value), "", ("=" & cookie.Value)).ToString & "; ")
- End If
- Next
- If str2.EndsWith("; ") Then
- str2 = str2.Substring(0, (str2.Length - 2))
- End If
- End If
- Return str2
- End If
- Me.SessionCookies = New List(Of HttpCookie)
- Return str2
- End Function
- Public Function GetCookies(ByVal Names As String(), ByVal Domain As String) As HttpCookie()
- Dim list As New List(Of HttpCookie)
- Dim str As String
- For Each str In Names
- Dim expression As HttpCookie = Me.FindCookie(str, Domain)
- If Not Information.IsNothing(expression) Then
- list.Add(expression)
- End If
- Next
- Return list.ToArray
- End Function
- Public Shared Function GetMIMEType(ByVal FilePath As String) As String
- If Connection.MIMETypes.ContainsKey(Path.GetExtension(FilePath.ToLower).Remove(0, 1)) Then
- Return Connection.MIMETypes.Item(Path.GetExtension(FilePath.ToLower).Remove(0, 1))
- End If
- Return "unknown/unknown"
- End Function
- Private Function GetRedirectUrl(ByVal RequestUri As String, ByVal Redirect As String) As String
- Dim str2 As String = String.Empty
- If Connection.IsValidUri(Redirect) Then
- Return Redirect
- End If
- If ((Redirect.StartsWith("&") Or Redirect.StartsWith("?")) Or RequestUri.EndsWith("/")) Then
- If (RequestUri.EndsWith("/") AndAlso Redirect.StartsWith("/")) Then
- Return (RequestUri & Redirect.Substring(1))
- End If
- Return (RequestUri & Redirect)
- End If
- If Redirect.StartsWith("/") Then
- Dim flag As Boolean = False
- Dim str3 As String
- For Each str3 In Strings.Split(Redirect, "/", -1, CompareMethod.Binary)
- If RequestUri.EndsWith(("/" & str3)) Then
- str2 = (RequestUri & Redirect.Substring(((Redirect.IndexOf(("/" & str3)) + str3.Length) + 1)))
- Exit For
- End If
- Next
- If Not flag Then
- str2 = (Interaction.IIf(RequestUri.StartsWith("https"), "https://", "http://").ToString & New Uri(RequestUri).Host & Redirect)
- End If
- End If
- Return str2
- End Function
- Private Function GetRequestHeaders(ByVal Request As HttpWebRequest) As String
- Return String.Format("Request Headers -----------------------------------{0}{1}", ChrW(13) & ChrW(10), Request.Headers.ToString)
- End Function
- Public Function GetResponse(ByVal Cooking As CookieContainer, ByVal Method As Verb, ByVal Uri As String, Optional ByVal PostData As Byte() = Nothing, Optional ByVal ExtraHeaders As NameValueCollection = Nothing) As HttpResponse
- Dim response3 As New HttpResponse
- Dim expression As Exception = Nothing
- Dim response As HttpWebResponse = Nothing
- Dim request As HttpWebRequest = Nothing
- Label_000C:
- Try
- Dim redirectUrl As String
- If Not Uri.StartsWith("http") Then
- Uri = ("http://" & Uri)
- End If
- If Not Connection.IsValidUri(Uri) Then
- expression = New Exception(String.Format("'{0}' is not a valid Uri.", Uri))
- Return response3
- End If
- request = Me.SendRequest(Cooking, Method, Uri, PostData, ExtraHeaders)
- response = CType(request.GetResponse, HttpWebResponse)
- Me.Cookies.Add(response.Cookies)
- Dim response4 As HttpResponse = response3
- response4.WebRequest = request
- response4.RequestUri = request.RequestUri.ToString
- response4.RequestHeaders = Me.GetRequestHeaders(request)
- If Not Information.IsNothing(PostData) Then
- Dim response6 As HttpResponse = response4
- response6.RequestHeaders = (response6.RequestHeaders & ChrW(13) & ChrW(10) & ChrW(13) & ChrW(10) & Me.Verbs(CInt(Method)) & Encoding.UTF8.GetString(PostData))
- End If
- response4.WebResponse = response
- response4.ResponseUri = response.ResponseUri.ToString
- response4.ResponseHeaders = Me.GetResponseHeaders(response)
- response4 = Nothing
- PostData = Nothing
- Dim response5 As HttpWebResponse = response
- If (response5.StatusCode = HttpStatusCode.OK) Then
- GoTo Label_01FF
- End If
- Select Case CInt(response5.StatusCode)
- Case &H12D, &H12E, &H12F, &H133
- redirectUrl = Me.GetRedirectUrl(response3.RequestUri, response5.Headers.Item("Location"))
- If Me.AutoRedirect Then
- Exit Select
- End If
- GoTo Label_01F1
- Case Else
- GoTo Label_028F
- End Select
- If (String.IsNullOrEmpty(redirectUrl) OrElse Me.IsBlackListed(redirectUrl)) Then
- GoTo Label_028F
- End If
- Uri = redirectUrl
- Method = Verb.GET
- Me.Referer = response3.RequestUri
- GoTo Label_000C
- Label_01F1:
- response3.RedirectUrl = redirectUrl
- GoTo Label_028F
- Label_01FF:
- Me.LastResponseUri = response.ResponseUri.ToString
- If Not Information.IsNothing(response5.Headers.Item(HttpResponseHeader.ContentType)) Then
- If response5.Headers.Item(HttpResponseHeader.ContentType).StartsWith("image") Then
- response3.Image = Image.FromStream(response5.GetResponseStream)
- Return response3
- End If
- If response5.Headers.Item(HttpResponseHeader.ContentType).StartsWith("video") Then
- Return response3
- End If
- End If
- Label_028F:
- response5 = Nothing
- response3.StatusCode = response.StatusCode
- response3.Html = Me.ProcessResponse(response)
- Me._LastResponseUri = Uri
- If Not ((response3.Html.ToLower.Contains("<meta http-equiv=""refresh") Or response3.Html.ToLower.Contains("window.parent.location.href =""")) Or response3.Html.ToLower.Contains("window.location.replace(""")) Then
- Return response3
- End If
- Dim str As String = String.Empty
- If response3.Html.ToLower.Contains("<meta http-equiv=""refresh") Then
- str = Me.GetRedirectUrl(response3.RequestUri, Connection.ParseMetaRefreshUrl(response3.Html))
- ElseIf response3.Html.ToLower.Contains("window.parent.location.href =""") Then
- str = Me.GetRedirectUrl(response3.RequestUri, Connection.ParseBetween(response3.Html, "window.parent.location.href=""", """", "window.parent.location.href=""".Length).Trim)
- ElseIf response3.Html.ToLower.Contains("window.location.replace(""") Then
- str = Me.GetRedirectUrl(response3.RequestUri, Connection.ParseBetween(response3.Html, "window.location.replace(""", """", "window.location.replace(""".Length).Trim)
- End If
- If Me.AllowMetaRedirect Then
- If String.IsNullOrEmpty(str) Then
- Return response3
- End If
- If Me.IsBlackListed(str) Then
- response3.RedirectUrl = str
- Return response3
- End If
- Uri = str
- Method = Verb.GET
- Me.Referer = response3.RequestUri
- GoTo Label_000C
- End If
- response3.RedirectUrl = str
- Catch exception1 As WebException
- ProjectData.SetProjectError(exception1)
- Dim ex As WebException = exception1
- ProjectData.SetProjectError(ex)
- Dim exception3 As WebException = ex
- expression = exception3
- If Not Information.IsNothing(exception3.Response) Then
- response3.WebResponse = CType(exception3.Response, HttpWebResponse)
- response3.StatusCode = response3.WebResponse.StatusCode
- response3.Html = Me.ProcessResponse(response3.WebResponse)
- End If
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- Catch exception5 As Exception
- ProjectData.SetProjectError(exception5)
- Dim exception4 As Exception = exception5
- ProjectData.SetProjectError(exception4)
- expression = exception4
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- Finally
- If Not Information.IsNothing(expression) Then
- response3.Error = Me.ProcessException(expression)
- End If
- If Not Information.IsNothing(response) Then
- response.Close()
- End If
- If response3.StatusCode.Equals(HttpStatusCode.GatewayTimeout) Then
- response3.TimedOut = True
- End If
- Me.Referer = String.Empty
- End Try
- Return response3
- End Function
- Public Function GetResponse(ByVal cooking As CookieContainer, Method As Connection.Verb, Uri As String, PostDataa As String, Optional ExtraHeaders As NameValueCollection = Nothing) As Connection.HttpResponse
- Dim postData As Byte() = Nothing
- Dim flag As Boolean = Not String.IsNullOrEmpty(PostDataa)
- If flag Then
- postData = Encoding.UTF8.GetBytes(PostDataa)
- End If
- Return Me.GetResponse(cooking, Method, Uri, postData, ExtraHeaders)
- End Function
- Public Function GetResponse(ByVal cooking As CookieContainer, ByVal Method As Verb, ByVal Uri As String, ByVal ExtraHeaders As NameValueCollection, ByVal Fields As NameValueCollection, ByVal ParamArray Upload As UploadData()) As HttpResponse
- Dim str As String = Guid.NewGuid.ToString.Replace("-", "")
- Me.ContentType = ("multipart/form-data; boundary=" & str)
- Dim stream As New MemoryStream
- Dim writer As New StreamWriter(stream)
- If (Not Fields Is Nothing) Then
- Dim num2 As Integer = (Fields.Count - 1)
- Dim i As Integer = 0
- Do While (i <= num2)
- writer.Write(("--" & str & ChrW(13) & ChrW(10)))
- writer.Write("Content-Disposition: form-data; name=""{0}""{1}{1}{2}{1}", Fields.Keys.Item(i), ChrW(13) & ChrW(10), Fields.Item(i))
- i += 1
- Loop
- End If
- If Not Information.IsNothing(Upload) Then
- Dim data As UploadData
- For Each data In Upload
- writer.Write(("--" & str & ChrW(13) & ChrW(10)))
- writer.Write("Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}", data.FieldName, data.FileName, ChrW(13) & ChrW(10))
- writer.Write(("Content-Type: " & data.ContentType & ChrW(13) & ChrW(10) & ChrW(13) & ChrW(10)))
- writer.Flush()
- If Not Information.IsNothing(data.Contents) Then
- stream.Write(data.Contents, 0, data.Contents.Length)
- End If
- writer.Write(ChrW(13) & ChrW(10))
- Next
- End If
- writer.Write("--{0}--{1}", str, ChrW(13) & ChrW(10))
- writer.Flush()
- writer = Nothing
- Me.ContentType = ("multipart/form-data; boundary=" & str)
- Dim response2 As HttpResponse = Me.GetResponse(cooking, Method, Uri, stream.ToArray, ExtraHeaders)
- Me.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"
- Return response2
- End Function
- Public Function GetResponse(ByVal cooking As CookieContainer, ByVal Method As Verb, ByVal Uri As String, ByVal ContType As String, ByVal Boundary As String, ByVal ExtraHeaders As NameValueCollection, ByVal Fields As NameValueCollection, ByVal ParamArray Upload As UploadData()) As HttpResponse
- Me.ContentType = ContType
- Dim stream As New MemoryStream
- Dim writer As New StreamWriter(stream)
- If (Not Fields Is Nothing) Then
- Dim num2 As Integer = (Fields.Count - 1)
- Dim i As Integer = 0
- Do While (i <= num2)
- writer.Write(("--" & Boundary & ChrW(13) & ChrW(10)))
- writer.Write("Content-Disposition: form-data; name=""{0}""{1}{1}{2}{1}", Fields.Keys.Item(i), ChrW(13) & ChrW(10), Fields.Item(i))
- i += 1
- Loop
- End If
- If Not Information.IsNothing(Upload) Then
- Dim data As UploadData
- For Each data In Upload
- writer.Write(("--" & Boundary & ChrW(13) & ChrW(10)))
- writer.Write("Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}", data.FieldName, data.FileName, ChrW(13) & ChrW(10))
- writer.Write(("Content-Type: " & data.ContentType & ChrW(13) & ChrW(10) & ChrW(13) & ChrW(10)))
- writer.Flush()
- If Not Information.IsNothing(data.Contents) Then
- stream.Write(data.Contents, 0, data.Contents.Length)
- End If
- writer.Write(ChrW(13) & ChrW(10))
- Next
- End If
- writer.Write("--{0}--{1}", Boundary, ChrW(13) & ChrW(10))
- writer.Flush()
- writer = Nothing
- Me.ContentType = ContType
- Dim response2 As HttpResponse = Me.GetResponse(cooking, Method, Uri, stream.ToArray, ExtraHeaders)
- Me.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"
- Return response2
- End Function
- Private Function GetResponseHeaders(ByVal Response As HttpWebResponse) As String
- Return String.Format("Response Headers -----------------------------------{0}{1}{0}{2}", ChrW(13) & ChrW(10), ("StatusCode: " & Conversions.ToString(CInt(Response.StatusCode)) & " " & Response.StatusDescription), Response.Headers.ToString)
- End Function
- Public Shared Function GetTimeStamp(ByVal Value As DateTime) As Long
- Return Convert.ToInt64(Value.Subtract(Convert.ToDateTime("1.1.1970 00:00:00")).TotalMilliseconds)
- End Function
- Public Shared Function ImageToBase64(ByVal Image As Image, ByVal Format As ImageFormat) As String
- Dim str2 As String = String.Empty
- Try
- Using stream As MemoryStream = New MemoryStream
- Image.Save(stream, Format)
- str2 = Convert.ToBase64String(stream.ToArray)
- End Using
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Debug.Print(ex.ToString)
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return str2
- End Function
- Public Shared Function ImageToBytes(ByVal Image As Image) As Byte()
- Using stream As MemoryStream = New MemoryStream
- Image.Save(stream, ImageFormat.Jpeg)
- stream.Close()
- Return stream.ToArray
- End Using
- End Function
- Private Function IsBlackListed(ByVal Url As String) As Boolean
- Dim str As String
- For Each str In Me.RedirectBlacklist
- If Url.ToLower.Contains(str.ToLower) Then
- Return True
- End If
- Next
- Return False
- End Function
- Public Shared Function IsValidIP(ByVal IP As String) As Boolean
- Return Regex.IsMatch(IP, "^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$")
- End Function
- Public Shared Function IsValidProxy(ByVal proxy As String) As Boolean
- Dim pattern As String = "[0-9]{1,3}\.[0-9}{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,4}"
- Dim regex As New Regex(pattern)
- Return regex.Match(proxy).Success
- End Function
- Public Shared Function IsValidUri(ByVal Url As String) As Boolean
- Return Regex.IsMatch(Url, "^(http)(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&=:%\$#_]*)?")
- End Function
- Public Function MakeProxy(ByVal proxy As String) As HttpProxy
- Dim proxy3 As HttpProxy = Nothing
- If Connection.IsValidProxy(proxy) Then
- Try
- Dim proxy4 As New HttpProxy
- proxy4.Server = Strings.Split(proxy, ":", -1, CompareMethod.Binary)(0)
- proxy4.Port = Conversions.ToInteger(Strings.Split(proxy, ":", -1, CompareMethod.Binary)(1))
- If (Connection.CountOccurance(proxy, ":", False) = 3) Then
- proxy4.UserName = Strings.Split(proxy, ":", -1, CompareMethod.Binary)(2)
- proxy4.Password = Strings.Split(proxy, ":", -1, CompareMethod.Binary)(3)
- End If
- Return proxy4
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Dim exception As Exception = ex
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- End If
- Return proxy3
- End Function
- Public Shared Function ParseBetween(ByVal Html As String, ByVal Before As String, ByVal After As String, ByVal Offset As Integer) As String
- If (Not String.IsNullOrEmpty(Html) AndAlso Html.Contains(Before)) Then
- Dim str2 As String = Html.Substring((Html.IndexOf(Before) + Offset))
- If (str2.Contains(After) AndAlso Not String.IsNullOrEmpty(After)) Then
- str2 = str2.Substring(0, str2.IndexOf(After))
- End If
- Return str2
- End If
- Return String.Empty
- End Function
- Public Shared Function ParseBetweenAll(ByVal Html As String, ByVal Before As String, ByVal After As String) As String()
- Dim list As New List(Of String)
- Dim list2 As New List(Of String)
- Dim list3 As List(Of String) = list2
- list3.AddRange(Regex.Split(Html, Before))
- list3.RemoveAt(0)
- Dim str As String
- For Each str In list2
- list.Add(Regex.Split(str, After)(0))
- Next
- list3 = Nothing
- Return list.ToArray
- End Function
- Private Sub ParseCookie(ByVal Data As String, ByVal Uri As Uri)
- Dim item As New HttpCookie
- Dim cookie As HttpCookie = item
- cookie.Name = Data.Split(New Char() {Convert.ToChar("=")})(0).Trim
- If Not Me.CookieBlacklist.Contains(cookie.Name) Then
- cookie.HttpOnly = False
- cookie.Secure = False
- If Data.Contains(";") Then
- cookie.Value = Data.Substring(0, Data.IndexOf(";"))
- cookie.Value = cookie.Value.Split(New Char() {Convert.ToChar("=")})(1).Trim
- Else
- cookie.Value = Data.Split(New Char() {Convert.ToChar("=")})(1).Trim
- End If
- If cookie.Value.ToLower.Equals("deleted") Then
- Dim expression As HttpCookie = Me.FindCookie(cookie.Name)
- If Not Information.IsNothing(expression) Then
- Me.RemoveCookie(expression)
- End If
- Else
- Dim str As String
- For Each str In Strings.Split(Data, ";", -1, CompareMethod.Binary)
- str = str.Trim
- If Not String.IsNullOrEmpty(str) Then
- If str.Contains("=") Then
- Dim str2 As String = str.Split(New Char() {Convert.ToChar("=")})(0).Trim
- Dim str3 As String = str.Substring((str.IndexOf("=") + 1)).Trim
- Dim str4 As String = str2.ToLower
- If (str4 = cookie.Name.ToLower) Then
- cookie.Value = str3
- ElseIf (str4 = "path") Then
- cookie.Path = str3
- ElseIf (str4 = "expires") Then
- str3 = Me.TrimDay(str3)
- If (str3.ToLower.EndsWith("utc") Or str3.ToLower.EndsWith("gmt")) Then
- str3 = str3.Substring(0, str3.ToLower.IndexOf(Interaction.IIf(str3.ToLower.EndsWith("utc"), "utc", "gmt").ToString)).Trim
- End If
- Try
- cookie.Expires = DateTime.Parse(str3)
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Debug.Print(ex.ToString)
- cookie.Expires = DateAndTime.Now.AddDays(3)
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- ElseIf (str4 = "domain") Then
- cookie.Domain = str3
- ElseIf (str4 = "httponly") Then
- cookie.HttpOnly = True
- ElseIf (str4 = "secure") Then
- cookie.Secure = True
- ElseIf (str4 = "version") Then
- cookie.Version = Convert.ToInt32(str3)
- ElseIf (str4 <> "max-age") Then
- Debug.Print(("unknown with value: " & str2 & " - " & str3))
- End If
- Else
- Dim str5 As String = str.ToLower
- If (str5 = "secure") Then
- cookie.Secure = True
- ElseIf (str5 = "httponly") Then
- cookie.HttpOnly = True
- Else
- Debug.Print(("unknown without value: " & str))
- End If
- End If
- End If
- Next
- If String.IsNullOrEmpty(cookie.Path) Then
- cookie.Path = Uri.AbsolutePath
- End If
- If String.IsNullOrEmpty(cookie.Domain) Then
- cookie.Domain = Uri.Host
- End If
- If cookie.Domain.StartsWith("www.") Then
- cookie.Domain = Strings.Replace(cookie.Domain, "www.", ".", 1, -1, CompareMethod.Binary)
- End If
- If Not String.IsNullOrEmpty(cookie.Value) Then
- Dim cookie4 As HttpCookie = Me.FindCookie(cookie.Name)
- If Not Information.IsNothing(cookie4) Then
- Me.RemoveCookie(cookie4)
- End If
- Me.SessionCookies.Add(item)
- End If
- End If
- cookie = Nothing
- End If
- End Sub
- Public Shared Function ParseFormClassText(ByVal Html As String, ByVal ClassName As String, Optional ByVal Highlighter As String = """") As String
- If String.IsNullOrEmpty(Html) Then
- Return String.Empty
- End If
- Dim str2 As String = String.Empty
- Try
- Html = Html.Substring((Html.IndexOf(("class=" & Highlighter & ClassName & Highlighter)) + 7))
- str2 = Connection.ParseBetween(Html, ("value=" & Highlighter), Highlighter, 7)
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return str2
- End Function
- Public Shared Function ParseFormIdText(ByVal Html As String, ByVal Id As String, Optional ByVal Highlighter As String = """") As String
- If String.IsNullOrEmpty(Html) Then
- Return String.Empty
- End If
- Dim str2 As String = String.Empty
- Try
- Html = Html.Substring((Html.IndexOf(("id=" & Highlighter & Id & Highlighter)) + 5))
- str2 = Connection.ParseBetween(Html, ("value=" & Highlighter), Highlighter, 7)
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return str2
- End Function
- Public Shared Function ParseFormNameText(ByVal Html As String, ByVal Name As String, Optional ByVal Highlighter As String = """") As String
- If String.IsNullOrEmpty(Html) Then
- Return String.Empty
- End If
- Dim str2 As String = String.Empty
- Try
- Html = Html.Substring((Html.IndexOf(("name=" & Highlighter & Name & Highlighter)) + 5))
- str2 = Connection.ParseBetween(Html, ("value=" & Highlighter), Highlighter, 7)
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return str2
- End Function
- Public Shared Function ParseMetaRefreshUrl(ByVal Html As String) As String
- If String.IsNullOrEmpty(Html) Then
- Return String.Empty
- End If
- Dim str2 As String = Html.ToLower
- Dim str3 As String = Connection.ParseBetween(Html.Substring((str2.IndexOf("<meta http-equiv=""refresh""") + "<meta http-equiv=""refresh""".Length)), "url=", """", "url=".Length).Trim
- If str3.StartsWith("'") Then
- str3 = str3.Substring(1)
- End If
- If str3.EndsWith("'") Then
- str3 = str3.Substring(0, (str3.Length - 1))
- End If
- Return str3
- End Function
- Private Sub ProcessCookies(ByVal Response As HttpWebResponse)
- Try
- If Information.IsNothing(Me.SessionCookies) Then
- Me.SessionCookies = New List(Of HttpCookie)
- End If
- Dim str As String = Response.Headers.Item("Set-Cookie")
- If (Not String.IsNullOrEmpty(str) AndAlso Not String.IsNullOrEmpty(str)) Then
- str = str.Replace("Mon,", "Mon").Replace("Tue,", "Tue").Replace("Wed,", "Wed").Replace("Thu,", "Thu").Replace("Fri,", "Fri").Replace("Sat,", "Sat").Replace("Sun,", "Sun").Replace("Monday,", "Mon").Replace("Tuesday,", "Tue").Replace("Wednesday,", "Wed").Replace("Thursday,", "Thurs").Replace("Friday,", "Fri").Replace("Saturday,", "Sat").Replace("Sunday,", "Sun")
- If Not str.Contains(",") Then
- Me.ParseCookie(str, Response.ResponseUri)
- Else
- Dim str2 As String
- For Each str2 In str.Split(New Char() {Convert.ToChar(",")})
- Me.ParseCookie(str2, Response.ResponseUri)
- Next
- End If
- End If
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Debug.Print(ex.ToString)
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- End Sub
- Private Function ProcessException(ByVal Ex As Object) As HttpError
- Dim erroro As New HttpError
- Dim message As String = String.Empty
- erroro.Exception = RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(Ex)))
- If TypeOf Ex Is WebException Then
- Dim exception As WebException = CType(Ex, WebException)
- If (Not Information.IsNothing(exception.Response) AndAlso CType(exception.Response, HttpWebResponse).StatusCode.Equals(HttpStatusCode.BadGateway)) Then
- message = exception.Message
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- erroro.IsProxyError = True
- End If
- End If
- If exception.Message.Contains("The underlying connection was closed:") Then
- message = exception.Message
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- erroro.IsProxyError = True
- End If
- ElseIf exception.Message.Contains("The remote server returned an error: (") Then
- message = exception.Message
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- erroro.IsProxyError = True
- End If
- Else
- Select Case CInt(exception.Status)
- Case 2
- If exception.Message.Trim.Equals("Unable to connect to the remote server") Then
- message = Interaction.IIf(Not String.IsNullOrEmpty(Me.Proxy.Server), "Could not connect to proxy server.", "Could not connect to server.").ToString
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- erroro.IsProxyError = True
- End If
- Else
- message = exception.Message
- End If
- GoTo Label_02CA
- Case 12
- message = Interaction.IIf(Not String.IsNullOrEmpty(Me.Proxy.Server), "Disconnected from proxy server.", exception.Message).ToString
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- erroro.IsProxyError = True
- End If
- GoTo Label_02CA
- Case 14
- message = "Timed out."
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- erroro.IsProxyError = True
- End If
- GoTo Label_02CA
- End Select
- message = exception.Message
- Debug.Print(("Exception else: " & Conversions.ToString(CInt(exception.Status)) & " - " & exception.Message))
- End If
- Else
- message = TryCast(Ex, Exception).Message
- End If
- Label_02CA:
- erroro.Message = message
- Return erroro
- End Function
- Private Function ProcessResponse(ByVal Response As HttpWebResponse) As String
- Dim str2 As String
- Try
- Dim builder As New StringBuilder
- Dim responseStream As Stream = Response.GetResponseStream
- If Response.ContentEncoding.ToLower.Contains("gzip") Then
- responseStream = New GZipStream(responseStream, CompressionMode.Decompress)
- ElseIf Response.ContentEncoding.ToLower.Contains("deflate") Then
- responseStream = New DeflateStream(responseStream, CompressionMode.Decompress)
- End If
- Using reader As StreamReader = New StreamReader(responseStream)
- Dim buffer As Char() = New Char(&H401 - 1) {}
- Dim i As Integer = reader.Read(buffer, 0, &H400)
- Do While (i > 0)
- Dim expression As New String(buffer, 0, i)
- expression = Strings.Replace(expression, ChrW(0), String.Empty, 1, -1, CompareMethod.Binary)
- builder.Append(expression)
- i = reader.Read(buffer, 0, &H400)
- Loop
- reader.Close()
- End Using
- responseStream.Close()
- responseStream.Dispose()
- responseStream = Nothing
- str2 = builder.ToString
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Dim exception As Exception = ex
- str2 = String.Empty
- ProjectData.ClearProjectError()
- Dim str As String = str2
- ProjectData.ClearProjectError()
- Return str
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return str2
- End Function
- Public Sub RemoveCookie(ByVal Name As String)
- Dim expression As HttpCookie = Me.FindCookie(Name)
- If Not Information.IsNothing(expression) Then
- Me.RemoveCookie(expression)
- End If
- End Sub
- Public Sub RemoveCookie(ByVal c As HttpCookie)
- Me.SessionCookies.Remove(c)
- End Sub
- Public Sub RemoveCookie(ByVal Name As String, ByVal Domain As String)
- Dim index As Integer = (Me.SessionCookies.Count - 1)
- Do While True
- Dim num2 As Integer = 0
- If (index < num2) Then
- Exit Do
- End If
- Dim cookie As HttpCookie = Me.SessionCookies.Item(index)
- If ((cookie.Name = Name) AndAlso (cookie.Domain = Domain)) Then
- Me.SessionCookies.RemoveAt(index)
- End If
- index = (index + -1)
- Loop
- End Sub
- Public Shared Function ResolveHost(ByVal Host As String) As IPAddress()
- Dim addressList As IPAddress()
- Try
- addressList = Dns.GetHostEntry(Host).AddressList
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Dim exception As Exception = ex
- addressList = Nothing
- ProjectData.ClearProjectError()
- Dim addressArray2 As IPAddress() = addressList
- ProjectData.ClearProjectError()
- Return addressArray2
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return addressList
- End Function
- Public Shared Function ResolveIP(ByRef IP As String) As String
- Dim hostName As String
- Try
- hostName = Dns.GetHostEntry(IP).HostName
- Catch exception1 As Exception
- ProjectData.SetProjectError(exception1)
- Dim ex As Exception = exception1
- ProjectData.SetProjectError(ex)
- Dim exception As Exception = ex
- hostName = String.Empty
- ProjectData.ClearProjectError()
- Dim str2 As String = hostName
- ProjectData.ClearProjectError()
- Return str2
- ProjectData.ClearProjectError()
- ProjectData.ClearProjectError()
- End Try
- Return hostName
- End Function
- Private Function SendRequest(ByVal Cooking As CookieContainer, Method As Verb, ByVal Uri As String, ByVal PostData As Byte(), ByVal ExtraHeaders As NameValueCollection) As HttpWebRequest
- If Information.IsNothing(ExtraHeaders) Then
- ExtraHeaders = New NameValueCollection
- End If
- Dim flag As Boolean = Uri.ToLower.StartsWith("https://")
- Dim request As HttpWebRequest = CType(WebRequest.Create(Uri), HttpWebRequest)
- Dim request2 As HttpWebRequest = request
- If UsedCookies = True Then
- request2.CookieContainer = Cooking
- End If
- request2.AllowWriteStreamBuffering = Me.AllowWriteStreamBuffering
- request2.AllowAutoRedirect = False
- request2.AutomaticDecompression = DecompressionMethods.None
- request2.ProtocolVersion = Me.Version
- request2.ServicePoint.Expect100Continue = Me.AllowExpect100
- request2.Timeout = Me.TimeOut
- request2.ServicePoint.GetType.GetProperty("HttpBehaviour", (BindingFlags.NonPublic Or BindingFlags.Instance)).SetValue(request2.ServicePoint, CByte(0), Nothing)
- request2.Proxy = Nothing
- If Not String.IsNullOrEmpty(Me.Proxy.Server) Then
- request2.Proxy = New WebProxy(Me.Proxy.Server, Me.Proxy.Port)
- If Not String.IsNullOrEmpty(Me.Proxy.UserName) Then
- request2.Proxy.Credentials = New NetworkCredential(Me.Proxy.UserName, Me.Proxy.Password)
- End If
- End If
- If Me.DebugMode Then
- Debug.Print(String.Format("[{0}] {1} >> {2}", DateAndTime.Now.ToString("hh:mm:ss tt").ToLower, Me.Verbs(CInt(Method)), Uri))
- End If
- request2.Method = Me.Verbs(CInt(Method))
- request2.Headers.Clear()
- request2.KeepAlive = Me.KeepAlive
- Dim headers As New WebHeaderCollection
- Dim headers2 As WebHeaderCollection = headers
- headers2.Add(HttpRequestHeader.Host, New Uri(Uri).Host)
- headers2.Add(HttpRequestHeader.UserAgent, Me.Useragent)
- If Not String.IsNullOrEmpty(Me.Accept) Then
- headers2.Add(HttpRequestHeader.Accept, Me.Accept)
- End If
- If Not String.IsNullOrEmpty(Me.AcceptLanguage) Then
- headers2.Add(HttpRequestHeader.AcceptLanguage, Me.AcceptLanguage)
- End If
- If Not String.IsNullOrEmpty(Me.AcceptEncoding) Then
- headers2.Add(HttpRequestHeader.AcceptEncoding, Me.AcceptEncoding)
- End If
- If Not String.IsNullOrEmpty(Me.AcceptCharset) Then
- headers2.Add(HttpRequestHeader.AcceptCharset, Me.AcceptCharset)
- End If
- If (ExtraHeaders.Count <> 0) Then
- Dim num4 As Integer = (ExtraHeaders.Count - 1)
- Dim j As Integer = 0
- Do While (j <= num4)
- Dim str As String = ExtraHeaders.Keys.Item(j)
- If (If(((((str = "Host") OrElse (str = "User-Agent")) OrElse ((str = "Referer") OrElse (str = "Accept"))) OrElse (((str = "Accept-Language") OrElse (str = "Accept-Charset")) OrElse (str = "Connection"))), 1, 0) = 0) Then
- headers2.Add(ExtraHeaders.Keys.Item(j), ExtraHeaders.Item(j))
- End If
- j += 1
- Loop
- End If
- If Not String.IsNullOrEmpty(Me.Referer) Then
- headers2.Add(HttpRequestHeader.Referer, Me.Referer)
- End If
- headers2 = Nothing
- Dim num2 As Integer = (headers.Count - 1)
- Dim i As Integer = 0
- Do While (i <= num2)
- Dim type As Type = GetType(WebHeaderCollection)
- type.GetMethod("AddWithoutValidate", (BindingFlags.NonPublic Or BindingFlags.Instance)).Invoke(request.Headers, New Object() {headers.Keys.Item(i), headers.Item(i)})
- i += 1
- Loop
- If Not Information.IsNothing(PostData) Then
- request2.SendChunked = Me.SendChunked
- request2.ContentType = Me.ContentType
- request2.ContentLength = PostData.Length
- Dim requestStream As Stream = request2.GetRequestStream
- requestStream.Write(PostData, 0, PostData.Length)
- requestStream.Close()
- requestStream.Dispose()
- requestStream = Nothing
- End If
- request2 = Nothing
- PostData = Nothing
- Me.LastRequestUri = Uri
- Return request
- End Function
- Private Sub SetUnsafeHeaderParsing(ByVal Allow As Boolean)
- Dim section As New SettingsSection
- Dim type As Type = Assembly.GetAssembly(section.GetType).GetType("System.Net.Configuration.SettingsSectionInternal")
- Dim args As Object() = Nothing
- Dim objectValue As Object = RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(type.InvokeMember("Section", (BindingFlags.GetProperty Or (BindingFlags.NonPublic Or BindingFlags.Static)), Nothing, Nothing, args))))
- type.GetField("useUnsafeHeaderParsing", (BindingFlags.NonPublic Or BindingFlags.Instance)).SetValue(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(objectValue))), Allow)
- End Sub
- Public Shared Function TimeStamp() As String
- Return Convert.ToInt32(DateAndTime.Now.Subtract(Convert.ToDateTime("1.1.1970 00:00:00")).TotalSeconds).ToString
- End Function
- Public Shared Function TimeStampLong() As String
- Return Convert.ToInt64(DateAndTime.Now.Subtract(Convert.ToDateTime("1.1.1970 00:00:00")).TotalMilliseconds).ToString
- End Function
- Private Function TrimDay(ByVal Value As String) As String
- Dim strArray As String() = New String() {"Mon", "Monday", "Tue", "Tues", "Tuesday", "Wed", "Wednesday", "Thu", "Thur", "Thurs", "Thursday", "Fri", "Friday", "Sat", "Saturday", "Sun", "Sunday"}
- Dim str As String
- For Each str In strArray
- If Value.ToLower.Contains(str.ToLower) Then
- Value = Value.ToLower.Replace(str.ToLower, String.Empty).Trim
- End If
- Next
- Return Value
- End Function
- Public Function TrimHtml(ByVal Data As String) As String
- Return Interaction.IIf(String.IsNullOrEmpty(Data), String.Empty, Regex.Replace(Data, "<.*?>", "")).ToString
- End Function
- Public Shared Function UrlEncode2(ByVal Value As String) As String
- Dim str As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
- Dim builder As New StringBuilder
- Dim str2 As String = Value
- Dim num2 As Integer = 0
- Dim length As Integer = str2.Length
- Do While (num2 < length)
- Dim truePart As Char = str2.Chars(num2)
- builder.Append(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(RuntimeHelpers.GetObjectValue(Interaction.IIf((str.IndexOf(truePart) <> -1), truePart, ("%" & String.Format("{0:X2}", Convert.ToInt32(truePart))))))))
- num2 += 1
- Loop
- Return builder.ToString
- End Function
- ' Properties
- Public Property Accept As String
- Get
- Return Me._Accept
- End Get
- Set(ByVal value As String)
- Me._Accept = value
- End Set
- End Property
- Public Property AcceptCharset As String
- Get
- Return Me._AcceptCharset
- End Get
- Set(ByVal value As String)
- Me._AcceptCharset = value
- End Set
- End Property
- Public Property AcceptEncoding As String
- Get
- Return Me._AcceptEncoding
- End Get
- Set(ByVal value As String)
- Me._AcceptEncoding = value
- End Set
- End Property
- Public Property AcceptLanguage As String
- Get
- Return Me._AcceptLanguage
- End Get
- Set(ByVal value As String)
- Me._AcceptLanguage = value
- End Set
- End Property
- Public Property AllowExpect100 As Boolean
- Get
- Return Me._AllowExpect100
- End Get
- Set(ByVal value As Boolean)
- Me._AllowExpect100 = value
- End Set
- End Property
- Public Property AllowMetaRedirect As Boolean
- Get
- Return Me._AllowMetaRedirect
- End Get
- Set(ByVal value As Boolean)
- Me._AllowMetaRedirect = value
- End Set
- End Property
- Public Property AllowWriteStreamBuffering As Boolean
- Get
- Return Me._AllowWriteStreamBuffering
- End Get
- Set(ByVal value As Boolean)
- Me._AllowWriteStreamBuffering = value
- End Set
- End Property
- Public Property AutoRedirect As Boolean
- Get
- Return Me._AutoRedirect
- End Get
- Set(ByVal value As Boolean)
- Me._AutoRedirect = value
- End Set
- End Property
- Public Property ContentType As String
- Get
- Return Me._ContentType
- End Get
- Set(ByVal value As String)
- Me._ContentType = value
- End Set
- End Property
- Public Property CustomCookies As HttpCookie()
- Get
- Return Me._CustomCookies
- End Get
- Set(ByVal value As HttpCookie())
- Me._CustomCookies = value
- End Set
- End Property
- Public Property DebugMode As Boolean
- Get
- Return Me._DebugMode
- End Get
- Set(ByVal value As Boolean)
- Me._DebugMode = value
- End Set
- End Property
- Public Property KeepAlive As Boolean
- Get
- Return Me._KeepAlive
- End Get
- Set(ByVal value As Boolean)
- Me._KeepAlive = value
- End Set
- End Property
- Public Property LastRequestUri As String
- Get
- Return Me._LastRequestUri
- End Get
- Set(ByVal value As String)
- Me._LastRequestUri = value
- End Set
- End Property
- Public Property LastResponseUri As String
- Get
- Return Me._LastResponseUri
- End Get
- Set(ByVal value As String)
- Me._LastResponseUri = value
- End Set
- End Property
- Public Property Proxy As HttpProxy
- Get
- Return Me._Proxy
- End Get
- Set(ByVal value As HttpProxy)
- Me._Proxy = value
- End Set
- End Property
- Public Property Referer As String
- Get
- Return Me._Referer
- End Get
- Set(ByVal value As String)
- Me._Referer = value
- End Set
- End Property
- Public Property SendChunked As Boolean
- Get
- Return Me._SendChunked
- End Get
- Set(ByVal value As Boolean)
- Me._SendChunked = value
- End Set
- End Property
- Public Property SendCookies As Boolean
- Get
- Return Me._SendCookies
- End Get
- Set(ByVal value As Boolean)
- Me._SendCookies = value
- End Set
- End Property
- Public Property StoreCookies As Boolean
- Get
- Return Me._StoreCookies
- End Get
- Set(ByVal value As Boolean)
- Me._StoreCookies = value
- End Set
- End Property
- Public Property TimeOut As Integer
- Get
- Return Me._TimeOut
- End Get
- Set(ByVal value As Integer)
- Me._TimeOut = value
- End Set
- End Property
- Public Property UseCustomCookies As Boolean
- Get
- Return Me._UseCustomCookies
- End Get
- Set(ByVal value As Boolean)
- Me._UseCustomCookies = value
- End Set
- End Property
- Public Property Useragent As String
- Get
- Return Me._UserAgent
- End Get
- Set(ByVal value As String)
- Me._UserAgent = value
- End Set
- End Property
- Public Property Version As Version
- Get
- Return Me._Version
- End Get
- Set(ByVal value As Version)
- Me._Version = value
- End Set
- End Property
- ' Fields
- Private _Accept As String = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
- Private _AcceptCharset As String = "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
- Private _AcceptEncoding As String = "gzip, deflate"
- Private _AcceptLanguage As String = "en-us,en;q=0.5"
- Private _AllowExpect100 As Boolean = False
- Private _AllowMetaRedirect As Boolean = True
- Private _AllowWriteStreamBuffering As Boolean = False
- Private _AutoRedirect As Boolean = True
- Private _ContentType As String = "application/x-www-form-urlencoded; charset=UTF-8"
- Private _CustomCookies As HttpCookie() = Nothing
- Private _DebugMode As Boolean = False
- Private _KeepAlive As Boolean = True
- Private _LastRequestUri As String = String.Empty
- Private _LastResponseUri As String = String.Empty
- Private _Proxy As HttpProxy = New HttpProxy
- Private _Referer As String = String.Empty
- Private _SendChunked As Boolean = False
- Private _SendCookies As Boolean = True
- Private _StoreCookies As Boolean = True
- Private _TimeOut As Integer = &HEA60
- Private _UseCustomCookies As Boolean = False
- Private _UserAgent As String = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0"
- Private _Version As Version = HttpVersion.Version11
- Private Const Base36 As String = "0123456789abcdefghijklmnopqrstuvwxyz"
- Public CookieBlacklist As List(Of String) = New List(Of String)
- Public Cookies As CookieContainer = New CookieContainer
- Private disposedValue As Boolean
- Private Shared ReadOnly MIMETypes As Dictionary(Of String, String)
- Public RedirectBlacklist As List(Of String) = New List(Of String)
- Private SessionCookies As List(Of HttpCookie)
- Private ReadOnly Verbs As String() = New String() {"GET", "POST", "PUT"}
- ' Nested Types
- <Serializable>
- Public Class HttpCookie
- ' Methods
- Public Sub New()
- Me.Name = String.Empty
- Me.Value = String.Empty
- Me.Domain = String.Empty
- Me.Path = String.Empty
- Me.Expires = New DateTime
- Me.HttpOnly = False
- Me.Secure = False
- Me.Version = -1
- End Sub
- Public Sub New(ByVal cName As String, ByVal cValue As String, ByVal cDomain As String)
- Me.Name = String.Empty
- Me.Value = String.Empty
- Me.Domain = String.Empty
- Me.Path = String.Empty
- Me.Expires = New DateTime
- Me.HttpOnly = False
- Me.Secure = False
- Me.Version = -1
- Me.Name = cName
- Me.Value = cValue
- Me.Domain = cDomain
- End Sub
- Public Sub New(ByVal cName As String, ByVal cValue As String, ByVal cDomain As String, ByVal cPath As String, ByVal cExpires As DateTime, ByVal cHttpOnly As Boolean, ByVal cSecure As Boolean, ByVal cVersion As Integer)
- Me.Name = String.Empty
- Me.Value = String.Empty
- Me.Domain = String.Empty
- Me.Path = String.Empty
- Me.Expires = New DateTime
- Me.HttpOnly = False
- Me.Secure = False
- Me.Version = -1
- Me.Name = cName
- Me.Value = cValue
- Me.Domain = cDomain
- Me.Path = cPath
- Me.Expires = cExpires
- Me.HttpOnly = cHttpOnly
- Me.Secure = cSecure
- Me.Version = cVersion
- End Sub
- ' Fields
- Public Domain As String
- Public Expires As DateTime
- Public HttpOnly As Boolean
- Public Name As String
- Public Path As String
- Public Secure As Boolean
- Public Value As String
- Public Version As Integer
- End Class
- Public Class HttpError
- ' Fields
- Public Exception As Object = Nothing
- Public Html As String = String.Empty
- Public IsProxyError As Boolean = False
- Public Message As String = String.Empty
- End Class
- <StructLayout(LayoutKind.Sequential)>
- Public Structure HttpProxy
- Public Server As String
- Public Port As Integer
- Public UserName As String
- Public Password As String
- Public Sub New(ByVal pServer As String, ByVal pPort As Integer, Optional ByVal pUserName As String = "", Optional ByVal pPassword As String = "")
- ' Me = New HttpProxy
- Me.Server = pServer
- Me.Port = pPort
- Me.UserName = pUserName
- Me.Password = pPassword
- End Sub
- End Structure
- Public Class HttpResponse
- ' Fields
- Public Bytes As Byte() = Nothing
- Public [Error] As HttpError = Nothing
- Public Html As String = String.Empty
- Public Image As Image = Nothing
- Public RedirectUrl As String = String.Empty
- Public RequestHeaders As String = String.Empty
- Public RequestUri As String = String.Empty
- Public ResponseHeaders As String = String.Empty
- Public ResponseUri As String = String.Empty
- Public StatusCode As HttpStatusCode
- Public Stream As Stream = Nothing
- Public TimedOut As Boolean = False
- Public WebRequest As HttpWebRequest = Nothing
- Public WebResponse As HttpWebResponse = Nothing
- End Class
- Public Enum MimicBrowser
- ' Fields
- Chrome = 2
- Custom = 3
- Firefox = 0
- InternetExplorer = 1
- End Enum
- <StructLayout(LayoutKind.Sequential)>
- Public Structure UploadData
- Public ContentType As String
- Public Contents As Byte()
- Public FileName As String
- Public FieldName As String
- Public Sub New(ByVal uContents As Byte(), ByVal uFileName As String, ByVal uFieldName As String)
- ' Me = New UploadData
- Me.Contents = uContents
- Me.FileName = uFileName
- Me.FieldName = uFieldName
- Me.ContentType = "application/octet-stream"
- End Sub
- End Structure
- Public Enum Verb
- ' Fields
- [GET] = 0
- POST = 1
- PUT = 2
- End Enum
- End Class
- End Namespace
Add Comment
Please, Sign In to add comment