1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
| Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Web
Imports System.Windows.Forms
Namespace Westwind.Tools.Http
''' <summary>
''' Summary description for wwHttp.
''' </summary>
Public Class wwHttp
''' <summary>
''' Fires progress events when using GetUrlEvents() to retrieve a URL.
''' </summary>
Public Event OnReceiveData As OnReceiveDataHandler
''' <summary>
''' Determines how data is POSTed when cPostBuffer is set.
''' 1 - UrlEncoded
''' 2 - Multi-Part form vars
''' 4 - XML (raw buffer content type: text/xml)
''' </summary>
Public Property PostMode() As Integer
Get
Return Me.nPostMode
End Get
Set(ByVal value As Integer)
Me.nPostMode = value
End Set
End Property
''' <summary>
''' User name used for Authentication.
''' To use the currently logged in user when accessing an NTLM resource you can use "AUTOLOGIN".
''' </summary>
Public Property Username() As String
Get
Return Me.cUsername
End Get
Set(ByVal value As String)
cUsername = value
End Set
End Property
''' <summary>
''' Password for Authentication.
''' </summary>
Public Property Password() As String
Get
Return Me.cPassword
End Get
Set(ByVal value As String)
Me.cPassword = value
End Set
End Property
''' <summary>
''' Address of the Proxy Server to be used.
''' Use optional DEFAULTPROXY value to specify that you want to IE's Proxy Settings
''' </summary>
Public Property ProxyAddress() As String
Get
Return Me.cProxyAddress
End Get
Set(ByVal value As String)
Me.cProxyAddress = value
End Set
End Property
''' <summary>
''' Semicolon separated Address list of the servers the proxy is not used for.
''' </summary>
Public Property ProxyBypass() As String
Get
Return Me.cProxyBypass
End Get
Set(ByVal value As String)
Me.cProxyBypass = value
End Set
End Property
''' <summary>
''' Username for a password validating Proxy. Only used if the proxy info is set.
''' </summary>
Public Property ProxyUsername() As String
Get
Return Me.cProxyUsername
End Get
Set(ByVal value As String)
Me.cProxyUsername = value
End Set
End Property
''' <summary>
''' Password for a password validating Proxy. Only used if the proxy info is set.
''' </summary>
Public Property ProxyPassword() As String
Get
Return Me.cProxyPassword
End Get
Set(ByVal value As String)
Me.cProxyPassword = value
End Set
End Property
''' <summary>
''' Timeout for the Web request in seconds. Times out on connection, read and send operations.
''' Default is 30 seconds.
''' </summary>
Public Property Timeout() As Integer
Get
Return Me.nConnectTimeout
End Get
Set(ByVal value As Integer)
Me.nConnectTimeout = value
End Set
End Property
''' <summary>
''' Error Message if the Error Flag is set or an error value is returned from a method.
''' </summary>
Public Property ErrorMsg() As String
Get
Return Me.cErrorMsg
End Get
Set(ByVal value As String)
Me.cErrorMsg = value
End Set
End Property
''' <summary>
''' Error flag if an error occurred.
''' </summary>
Public Property [Error]() As Boolean
Get
Return Me.bError
End Get
Set(ByVal value As Boolean)
Me.bError = value
End Set
End Property
''' <summary>
''' Determines whether errors cause exceptions to be thrown. By default errors
''' are handled in the class and the Error property is set for error conditions.
''' (not implemented at this time).
''' </summary>
Public Property ThrowExceptions() As Boolean
Get
Return bThrowExceptions
End Get
Set(ByVal value As Boolean)
Me.bThrowExceptions = value
End Set
End Property
''' <summary>
''' If set to a non-zero value will automatically track cookies. The number assigned is the cookie count.
''' </summary>
Public Property HandleCookies() As Boolean
Get
Return Me.bHandleCookies
End Get
Set(ByVal value As Boolean)
Me.bHandleCookies = value
End Set
End Property
Public Property Cookies() As CookieCollection
Get
Return Me.oCookies
End Get
Set(ByVal value As CookieCollection)
Me.Cookies = value
End Set
End Property
Public Property WebResponse() As HttpWebResponse
Get
Return Me.oWebResponse
End Get
Set(ByVal value As HttpWebResponse)
Me.oWebResponse = value
End Set
End Property
Public Property WebRequest() As HttpWebRequest
Get
Return Me.oWebRequest
End Get
Set(ByVal value As HttpWebRequest)
Me.oWebRequest = value
End Set
End Property
' *** member properties
'string cPostBuffer = "";
Private oPostStream As MemoryStream
Private oPostData As BinaryWriter
Private nPostMode As Integer = 1
Private nConnectTimeout As Integer = 30
Private cUserAgent As String = "West Wind HTTP .NET"
Private cUsername As String = ""
Private cPassword As String = ""
Private cProxyAddress As String = ""
Private cProxyBypass As String = ""
Private cProxyUsername As String = ""
Private cProxyPassword As String = ""
Private bThrowExceptions As Boolean = False
Private bHandleCookies As Boolean = False
Private cErrorMsg As String = ""
Private bError As Boolean = False
Private oWebResponse As HttpWebResponse
Private oWebRequest As HttpWebRequest
Private oCookies As CookieCollection
Private cMultiPartBoundary As String = "-----------------------------7cf2a327f01ae"
Public Sub wwHTTP()
'
' TODO: Add constructor logic here
''
End Sub
''' <summary>
''' Adds POST form variables to the request buffer.
''' HttpPostMode determines how parms are handled.
''' 1 - UrlEncoded Form Variables. Uses key and value pairs (ie. "Name","Rick") to create URLEncoded content
''' 2 - Multi-Part Forms - not supported
''' 4 - XML block - Post a single XML block. Pass in as Key (1st Parm)
''' other - raw content buffer. Just assign to Key.
''' </summary>
''' <param name="Key">Key value or raw buffer depending on post type</param>
''' <param name="Value">Value to store. Used only in key/value pair modes</param>
Public Sub AddPostKey(ByVal Key As String, ByVal Value As Byte())
If Me.oPostData Is Nothing Then
Me.oPostStream = New MemoryStream()
Me.oPostData = New BinaryWriter(Me.oPostStream)
End If
If Key = "RESET" Then
Me.oPostStream = New MemoryStream()
Me.oPostData = New BinaryWriter(Me.oPostStream)
End If
Select Case Me.nPostMode
Case 1
Me.oPostData.Write(Encoding.GetEncoding(1252).GetBytes(Key + "=" + System.Web.HttpUtility.UrlEncode(Value) + "&"))
Case 2
Me.oPostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + Me.cMultiPartBoundary + "" & Chr(13) & "" & Chr(10) & "" + "Content-Disposition: form-data; name=""" + Key + """" & Chr(13) & "" & Chr(10) & "" & Chr(13) & "" & Chr(10) & ""))
Me.oPostData.Write(Value)
Me.oPostData.Write(Encoding.GetEncoding(1252).GetBytes("" & Chr(13) & "" & Chr(10) & ""))
Case Else
Me.oPostData.Write(Value)
End Select
End Sub
Public Sub AddPostKey(ByVal Key As String, ByVal Value As String)
Me.AddPostKey(Key, Encoding.GetEncoding(1252).GetBytes(Value))
End Sub
''' <summary>
''' Adds a fully self contained POST buffer to the request.
''' Works for XML or previously encoded content.
''' </summary>
''' <param name="PostBuffer"></param>
Public Sub AddPostKey(ByVal FullPostBuffer As String)
Me.oPostData.Write(Encoding.GetEncoding(1252).GetBytes(FullPostBuffer))
End Sub
Public Function AddPostFile(ByVal Key As String, ByVal FileName As String) As Boolean
Dim lcFile As Byte()
If Me.nPostMode <> 2 Then
Me.cErrorMsg = "File upload allowed only with Multi-part forms"
Me.bError = True
Return False
End If
Try
Dim loFile As New FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)
lcFile = New Byte(CInt(loFile.Length)) {}
loFile.Read(lcFile, 0, CInt(loFile.Length))
loFile.Close()
Catch e As Exception
Me.cErrorMsg = e.Message
Me.bError = True
Return False
End Try
Me.oPostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + Me.cMultiPartBoundary + "" & Chr(13) & "" & Chr(10) & "" + "Content-Disposition: form-data; name=""" + Key + """ filename=""" + New FileInfo(FileName).Name + """" & Chr(13) & "" & Chr(10) & "" & Chr(13) & "" & Chr(10) & ""))
Me.oPostData.Write(lcFile)
Me.oPostData.Write(Encoding.GetEncoding(1252).GetBytes("" & Chr(13) & "" & Chr(10) & ""))
Return True
End Function
''' <summary>
''' Return a the result from an HTTP Url into a StreamReader.
''' Client code should call Close() on the returned object when done reading.
''' </summary>
''' <param name="Url">Url to retrieve.</param>
''' <param name="WebRequest">An HttpWebRequest object that can be passed in with properties preset.</param>
''' <returns></returns>
Protected Function GetUrlStream(ByVal Url As String, ByVal Request As HttpWebRequest) As StreamReader
Try
Me.bError = False
Me.cErrorMsg = ""
If Request Is Nothing Then
Request = DirectCast(System.Net.WebRequest.Create(Url), HttpWebRequest)
End If
Request.UserAgent = Me.cUserAgent
Request.Timeout = Me.nConnectTimeout * 1000
' *** Save for external access
Me.oWebRequest = Request
' *** Handle Security for the request
If Me.cUsername.Length > 0 Then
If Me.cUsername = "AUTOLOGIN" Then
Request.Credentials = CredentialCache.DefaultCredentials
Else
Request.Credentials = New NetworkCredential(Me.cUsername, Me.cPassword)
End If
End If
' *** Handle Proxy Server configuration
If Me.cProxyAddress.Length > 0 Then
If Me.cProxyAddress = "DEFAULTPROXY" Then
Request.Proxy = New WebProxy()
Request.Proxy = WebProxy.GetDefaultProxy()
Else
Dim loProxy As New WebProxy(Me.cProxyAddress, True)
If Me.cProxyBypass.Length > 0 Then
loProxy.BypassList = Me.cProxyBypass.Split(";"c)
End If
If Me.cProxyUsername.Length > 0 Then
loProxy.Credentials = New NetworkCredential(Me.cProxyUsername, Me.cProxyPassword)
End If
Request.Proxy = loProxy
End If
End If
' *** Handle cookies - automatically re-assign
If Me.bHandleCookies Then
Request.CookieContainer = New CookieContainer()
If Not Me.oCookies Is Nothing AndAlso Me.oCookies.Count > 0 Then
Request.CookieContainer.Add(Me.oCookies)
End If
End If
' *** Deal with the POST buffer if any
If Not Me.oPostData Is Nothing Then
Request.Method = "POST"
Select Case Me.nPostMode
Case 2
Request.ContentType = "multipart/form-data; boundary=" + Me.cMultiPartBoundary
Me.oPostData.Write(Encoding.GetEncoding(1252).GetBytes("--" + Me.cMultiPartBoundary + "" & Chr(13) & "" & Chr(10) & ""))
Case 4
Request.ContentType = "text/xml"
Case Else
Request.ContentType = "application/x-www-form-urlencoded"
' strip off any trailing & which can cause problems with some
' http servers
' if (this.cPostBuffer.EndsWith("&"))
' this.cPostBuffer = this.cPostBuffer.Substring(0,this.cPostBuffer.Length-1);
End Select
Dim loPostData As Stream = Request.GetRequestStream()
'loPostData.Write(lcPostData,0,lcPostData.Length);
Me.oPostStream.WriteTo(loPostData)
'*** Close the memory stream
Me.oPostStream.Close()
Me.oPostStream = Nothing
'*** Close the Binary Writer
Me.oPostData.Close()
Me.oPostData = Nothing
'*** Close Request Stream
loPostData.Close()
' *** clear the POST buffer
'this.cPostBuffer = "";
End If
' *** Retrieve the response headers
Dim Response As HttpWebResponse = DirectCast(Request.GetResponse(), HttpWebResponse)
' ** Save cookies the server sends
If Me.bHandleCookies Then
If Response.Cookies.Count > 0 Then
If Me.oCookies Is Nothing Then
Me.oCookies = Response.Cookies
Else
' ** If we already have cookies update the list
For Each oRespCookie As Cookie In Response.Cookies
Dim bMatch As Boolean = False
For Each oReqCookie As Cookie In Me.oCookies
If oReqCookie.Name = oRespCookie.Name Then
oReqCookie.Value = oRespCookie.Name
bMatch = True
Exit For
End If
Next
If Not bMatch Then
Me.oCookies.Add(oRespCookie)
End If
Next
End If
End If
End If
' *** Save the response object for external access
Me.oWebResponse = Response
Dim enc As Encoding
Try
If Response.ContentEncoding.Length > 0 Then
enc = Encoding.GetEncoding(Response.ContentEncoding)
Else
enc = Encoding.GetEncoding(1252)
End If
Catch
' *** Invalid encoding passed
enc = Encoding.GetEncoding(1252)
End Try
' *** drag to a stream
Dim strResponse As New StreamReader(Response.GetResponseStream(), enc)
Return strResponse
Catch e As Exception
If Me.bThrowExceptions Then
Throw e
End If
Me.cErrorMsg = e.Message
Me.bError = True
Return Nothing
End Try
End Function
''' <summary>
''' Return a the result from an HTTP Url into a StreamReader.
''' Client code should call Close() on the returned object when done reading.
''' </summary>
''' <param name="Url">Url to retrieve.</param>
''' <returns></returns>
Public Function GetUrlStream(ByVal Url As String) As StreamReader
Dim oHttpWebRequest As HttpWebRequest = Nothing
Return Me.GetUrlStream(Url, oHttpWebRequest)
End Function
''' <summary>
''' Return a the result from an HTTP Url into a StreamReader.
''' Client code should call Close() on the returned object when done reading.
''' </summary>
''' <param name="Request">A Request object</param>
''' <returns></returns>
Public Function GetUrlStream(ByVal Request As HttpWebRequest) As StreamReader
Return Me.GetUrlStream(Request.RequestUri.AbsoluteUri, Request)
End Function
''' <summary>
''' Return a the result from an HTTP Url into a string.
''' </summary>
''' <param name="Url">Url to retrieve.</param>
''' <returns></returns>
Public Function GetUrl(ByVal Url As String) As String
Dim oHttpResponse As StreamReader = Me.GetUrlStream(Url)
If oHttpResponse Is Nothing Then
Return ""
End If
Dim lcResult As String = oHttpResponse.ReadToEnd()
oHttpResponse.Close()
Return lcResult
End Function
''' <summary>
''' Return a the result from an HTTP Url into a string.
''' </summary>
''' <param name="Url">Url to retrieve.</param>
''' <returns></returns>
Public Function GetUrlBytes(ByVal Url As String) As Byte()
Dim oHttpResponse As StreamReader = Me.GetUrlStream(Url)
If oHttpResponse Is Nothing Then
Return Nothing
End If
Dim lcResult As String = oHttpResponse.ReadToEnd()
oHttpResponse.Close()
Return Nothing
End Function
''' <summary>
''' Retrieves URL with events in the OnReceiveData event.
''' </summary>
''' <param name="Url"></param>
''' <param name="BufferSize"></param>
''' <returns></returns>
Public Function GetUrlEvents(ByVal Url As String, ByVal BufferSize As Long) As String
Dim oHttpResponse As StreamReader = Me.GetUrlStream(Url)
If oHttpResponse Is Nothing Then
Return ""
End If
Dim lnSize As Long = BufferSize
If Me.oWebResponse.ContentLength > 0 Then
lnSize = Me.oWebResponse.ContentLength
Else
lnSize = 0
End If
Dim enc As Encoding = Encoding.GetEncoding(1252)
Dim loWriter As New StringBuilder(CInt(lnSize))
Dim lcTemp As Char() = New Char(CInt(BufferSize)) {}
Dim oArgs As New OnReceiveDataEventArgs()
oArgs.TotalBytes = lnSize
lnSize = 1
Dim lnCount As Integer = 0
Dim lnTotalBytes As Long = 0
While lnSize > 0
lnSize = oHttpResponse.Read(lcTemp, 0, CInt(BufferSize))
If lnSize > 0 Then
loWriter.Append(lcTemp, 0, CInt(lnSize))
System.Math.Max(System.Threading.Interlocked.Increment(lnCount), lnCount - 1)
lnTotalBytes += lnSize
oArgs.CurrentByteCount = lnTotalBytes
oArgs.NumberOfReads = lnCount
oArgs.CurrentChunk = lcTemp
RaiseEvent OnReceiveData(Me, oArgs)
' *** Check for cancelled flag
If oArgs.Cancel Then
GoTo CloseDown
End If
End If
End While
CloseDown:
oHttpResponse.Close()
If Not oArgs.Cancel Then
' *** Update the event handler
oArgs.Done = True
RaiseEvent OnReceiveData(Me, oArgs)
End If
' return lcHtml;
Return loWriter.ToString()
End Function
Public Delegate Sub OnReceiveDataHandler(ByVal sender As Object, ByVal e As OnReceiveDataEventArgs)
Public Class OnReceiveDataEventArgs
Public CurrentByteCount As Long = 0
Public TotalBytes As Long = 0
Public NumberOfReads As Integer = 0
Public CurrentChunk As Char()
Public Done As Boolean = False
Public Cancel As Boolean = False
End Class
End Class
End Namespace |
Partager