This repository was archived by the owner on Mar 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebResponse.cls
414 lines (348 loc) · 13.4 KB
/
WebResponse.cls
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
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
Persistable = 0 'NotPersistable
DataBindingBehavior = 0 'vbNone
DataSourceBehavior = 0 'vbNone
MTSTransactionMode = 0 'NotAnMTSObject
END
Attribute VB_Name = "WebResponse"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
''
' WebResponse v4.1.6
' (c) Tim Hall - https://github.com/VBA-tools/VBA-Web
'
' Wrapper for http/cURL responses that includes parsed Data based on WebRequest.ResponseFormat.
'
' Usage:
' ```VB.net
' Dim Response As WebResponse
' Set Response = Client.Execute(Request)
'
' If Response.StatusCode = WebStatusCode.Ok Then
' ' Response.Headers, Response.Cookies
' ' Response.Data -> Parsed Response.Content based on Request.ResponseFormat
' ' Response.Body -> Raw response bytes
' Else
' Debug.Print "Error: " & Response.StatusCode & " - " & Response.Content
' End If
' ```
'
' Errors:
' 11030 / 80042b16 / -2147210474 - Error creating from http
' 11031 / 80042b17 / -2147210473 - Error creating from cURL
' 11032 / 80042b18 / -2147210472 - Error extracting headers
'
' @class WebResponse
' @author [email protected]
' @license MIT (http://www.opensource.org/licenses/mit-license.php)
'' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ '
Option Explicit
Private web_CrLf As String
' --------------------------------------------- '
' Properties
' --------------------------------------------- '
''
' Status code that the server returned (e.g. 200).
'
' @property StatusCode
' @type WebStatusCode
''
Public StatusCode As WebStatusCode
''
' Status string that the server returned (e.g. `404 -> "Not Found"`)
'
' @property StatusDescription
' @type String
''
Public StatusDescription As String
''
' Content string that the server returned.
'
' @property Content
' @type String
''
Public Content As String
''
' Raw bytes for the response.
'
' @property Body
' @type Byte()
''
Public Body As Variant
''
' Parsed `Content` or `Body` based on the `WebRequest.ResponseFormat`.
'
' @property Data
' @type Dictionary|Collection
''
Public data As Object
''
' Headers that were included with the response.
' (`Collection` of `KeyValue`)
'
' @property Headers
' @type Collection
''
Public Headers As Collection
''
' Cookies that were included with the response.
' (`Collection` of `KeyValue`)
'
' @property Cookies
' @type Collection
''
Public Cookies As Collection
' ============================================= '
' Public Methods
' ============================================= '
''
' Helper for updating the response with the given updated response values.
' Useful for `ByRef` cases to update response in place.
'
' @method Update
' @param Updated {WebResponse} Updated `WebResponse` to pull updated values from
''
Public Sub Update(Updated As WebResponse)
Me.StatusCode = Updated.StatusCode
Me.StatusDescription = Updated.StatusDescription
Me.Content = Updated.Content
Me.Body = Updated.Body
Set Me.Headers = Updated.Headers
Set Me.Cookies = Updated.Cookies
Set Me.data = Updated.data
End Sub
''
' Create response from http
'
' @internal
' @method CreateFromHttp
' @param {WebClient} Client
' @param {WebRequest} Request
' @param {WinHttpRequest} Http
' @throws 11030 / 80042b16 / -2147210474 - Error creating from http
''
Public Sub CreateFromHttp(Client As WebClient, Request As WebRequest, Http As Object)
On Error GoTo web_ErrorHandling
Me.StatusCode = Http.Status
Me.StatusDescription = Http.StatusText
Me.Content = Http.ResponseText
Me.Body = Http.ResponseBody
web_LoadValues Http.GetAllResponseHeaders, Me.Content, Me.Body, Request
Exit Sub
web_ErrorHandling:
Dim web_ErrorDescription As String
web_ErrorDescription = "An error occurred while creating response from http" & vbNewLine & _
Err.Number & VBA.IIf(Err.Number < 0, " (" & VBA.LCase$(VBA.Hex$(Err.Number)) & ")", "") & ": " & Err.Description
WebHelpers.LogError web_ErrorDescription, "WebResponse.CreateFromHttp", 11030 + vbObjectError
Err.Raise 11030 + vbObjectError, "WebResponse.CreateFromHttp", web_ErrorDescription
End Sub
''
' Create response from cURL
'
' @internal
' @method CreateFromCurl
' @param {WebClient} Client
' @param {WebRequest} Request
' @param {String} Result
' @throws 11031 / 80042b17 / -2147210473 - Error creating from cURL
''
Public Sub CreateFromCurl(Client As WebClient, Request As WebRequest, Result As String)
On Error GoTo web_ErrorHandling
Dim web_Lines() As String
web_Lines = VBA.Split(Result, web_CrLf)
Me.StatusCode = web_ExtractStatusFromCurlResponse(web_Lines)
Me.StatusDescription = web_ExtractStatusTextFromCurlResponse(web_Lines)
Me.Content = web_ExtractResponseTextFromCurlResponse(web_Lines)
Me.Body = WebHelpers.StringToAnsiBytes(Me.Content)
web_LoadValues web_ExtractHeadersFromCurlResponse(web_Lines), Me.Content, Me.Body, Request
Exit Sub
web_ErrorHandling:
Dim web_ErrorDescription As String
web_ErrorDescription = "An error occurred while creating response from cURL" & vbNewLine & _
Err.Number & VBA.IIf(Err.Number < 0, " (" & VBA.LCase$(VBA.Hex$(Err.Number)) & ")", "") & ": " & Err.Description
WebHelpers.LogError web_ErrorDescription, "WebResponse.CreateFromCurl", 11031 + vbObjectError
Err.Raise 11031 + vbObjectError, "WebResponse.CreateFromCurl", web_ErrorDescription
End Sub
''
' Extract headers from response headers
'
' @internal
' @method ExtractHeaders
' @param {String} ResponseHeaders
' @return {Collection} Headers
' @throws 11032 / 80042b18 / -2147210472 - Error extracting headers
''
Public Function ExtractHeaders(ResponseHeaders As String) As Collection
On Error GoTo web_ErrorHandling
Dim web_Lines As Variant
Dim web_i As Integer
Dim web_Headers As New Collection
Dim web_Header As Dictionary
Dim web_ColonPosition As Long
Dim web_Multiline As Boolean
web_Lines = VBA.Split(ResponseHeaders, web_CrLf)
For web_i = LBound(web_Lines) To (UBound(web_Lines) + 1)
If web_i > UBound(web_Lines) Then
web_Headers.Add web_Header
ElseIf web_Lines(web_i) <> "" Then
web_ColonPosition = VBA.InStr(1, web_Lines(web_i), ":")
If web_ColonPosition = 0 And Not web_Header Is Nothing Then
' Assume part of multi-line header
web_Multiline = True
ElseIf web_Multiline Then
' Close out multi-line string
web_Multiline = False
web_Headers.Add web_Header
ElseIf Not web_Header Is Nothing Then
' Add previous header
web_Headers.Add web_Header
End If
If Not web_Multiline Then
Set web_Header = WebHelpers.CreateKeyValue( _
key:=VBA.Trim(VBA.Mid$(web_Lines(web_i), 1, web_ColonPosition - 1)), _
Value:=VBA.Trim(VBA.Mid$(web_Lines(web_i), web_ColonPosition + 1, VBA.Len(web_Lines(web_i)))) _
)
Else
web_Header("Value") = web_Header("Value") & web_CrLf & web_Lines(web_i)
End If
End If
Next web_i
Set ExtractHeaders = web_Headers
Exit Function
web_ErrorHandling:
Dim web_ErrorDescription As String
web_ErrorDescription = "An error occurred while extracting headers" & vbNewLine & _
Err.Number & VBA.IIf(Err.Number < 0, " (" & VBA.LCase$(VBA.Hex$(Err.Number)) & ")", "") & ": " & Err.Description
WebHelpers.LogError web_ErrorDescription, "WebResponse.CreateFromCurl", 11032 + vbObjectError
Err.Raise 11032 + vbObjectError, "WebResponse.CreateFromCurl", web_ErrorDescription
End Function
''
' Extract cookies from response headers
'
' @internal
' @method ExtractCookies
' @param {Collection} Headers
' @return {Collection} Cookies
''
Public Function ExtractCookies(Headers As Collection) As Collection
Dim web_Header As Dictionary
Dim web_Cookie As String
Dim web_Key As String
Dim web_Value As String
Dim web_Cookies As New Collection
For Each web_Header In Headers
If web_Header("Key") = "Set-Cookie" Then
web_Cookie = web_Header("Value")
If VBA.InStr(1, web_Cookie, "=") > 0 Then
web_Key = VBA.Mid$(web_Cookie, 1, VBA.InStr(1, web_Cookie, "=") - 1)
web_Value = VBA.Mid$(web_Cookie, VBA.InStr(1, web_Cookie, "=") + 1, VBA.Len(web_Cookie))
' Ignore text after semi-colon
If VBA.InStr(1, web_Value, ";") > 0 Then
web_Value = VBA.Mid$(web_Value, 1, VBA.InStr(1, web_Value, ";") - 1)
End If
' Ignore surrounding quotes
If VBA.Left$(web_Value, 1) = """" Then
web_Value = VBA.Mid$(web_Value, 2, VBA.Len(web_Value) - 2)
End If
web_Cookies.Add WebHelpers.CreateKeyValue(web_Key, WebHelpers.UrlDecode(web_Value, PlusAsSpace:=False, EncodingMode:=UrlEncodingMode.CookieUrlEncoding))
Else
WebHelpers.LogWarning _
"Unrecognized cookie format: " & web_Cookie, "WebResponse.ExtractCookies"
End If
End If
Next web_Header
Set ExtractCookies = web_Cookies
End Function
' ============================================= '
' Private Functions
' ============================================= '
Private Sub web_LoadValues(web_Headers As String, web_Content As String, web_Body As Variant, web_Request As WebRequest)
' Convert content to data by format
If web_Request.ResponseFormat <> WebFormat.PlainText Then
On Error Resume Next
Set Me.data = _
WebHelpers.ParseByFormat(web_Content, web_Request.ResponseFormat, web_Request.CustomResponseFormat, web_Body)
If Err.Number <> 0 Then
WebHelpers.LogError Err.Description, Err.Source, Err.Number
Err.Clear
End If
On Error GoTo 0
End If
' Extract headers
Set Me.Headers = ExtractHeaders(web_Headers)
' Extract cookies
Set Me.Cookies = ExtractCookies(Me.Headers)
End Sub
Private Function web_ExtractStatusFromCurlResponse(web_CurlResponseLines() As String) As Long
Dim web_StatusLineParts() As String
web_StatusLineParts = VBA.Split(web_CurlResponseLines(web_FindStatusLine(web_CurlResponseLines)), " ")
web_ExtractStatusFromCurlResponse = VBA.CLng(web_StatusLineParts(1))
End Function
Private Function web_ExtractStatusTextFromCurlResponse(web_CurlResponseLines() As String) As String
Dim web_StatusLineParts() As String
Dim web_i As Long
Dim web_StatusText As String
web_StatusLineParts = VBA.Split(web_CurlResponseLines(web_FindStatusLine(web_CurlResponseLines)), " ", 3)
web_ExtractStatusTextFromCurlResponse = web_StatusLineParts(2)
End Function
Private Function web_ExtractHeadersFromCurlResponse(web_CurlResponseLines() As String) As String
Dim web_StatusLineIndex As Long
Dim web_BlankLineIndex As Long
Dim web_HeaderLines() As String
Dim web_WriteIndex As Long
Dim web_ReadIndex As Long
' Find status line and blank line before body
web_StatusLineIndex = web_FindStatusLine(web_CurlResponseLines)
web_BlankLineIndex = web_FindBlankLine(web_CurlResponseLines)
' Extract headers string
ReDim web_HeaderLines(0 To web_BlankLineIndex - 2 - web_StatusLineIndex)
web_WriteIndex = 0
For web_ReadIndex = (web_StatusLineIndex + 1) To web_BlankLineIndex - 1
web_HeaderLines(web_WriteIndex) = web_CurlResponseLines(web_ReadIndex)
web_WriteIndex = web_WriteIndex + 1
Next web_ReadIndex
web_ExtractHeadersFromCurlResponse = VBA.Join$(web_HeaderLines, web_CrLf)
End Function
Private Function web_ExtractResponseTextFromCurlResponse(web_CurlResponseLines() As String) As String
Dim web_BlankLineIndex As Long
Dim web_BodyLines() As String
Dim web_WriteIndex As Long
Dim web_ReadIndex As Long
' Find blank line before body
web_BlankLineIndex = web_FindBlankLine(web_CurlResponseLines)
' Extract body string
ReDim web_BodyLines(0 To UBound(web_CurlResponseLines) - web_BlankLineIndex - 1)
web_WriteIndex = 0
For web_ReadIndex = web_BlankLineIndex + 1 To UBound(web_CurlResponseLines)
web_BodyLines(web_WriteIndex) = web_CurlResponseLines(web_ReadIndex)
web_WriteIndex = web_WriteIndex + 1
Next web_ReadIndex
web_ExtractResponseTextFromCurlResponse = VBA.Join$(web_BodyLines, web_CrLf)
End Function
Private Function web_FindStatusLine(web_CurlResponseLines() As String) As Long
' Special case for cURL: 100 Continue is included before final status code
' -> ignore 100 and find final status code (next non-100 status code)
For web_FindStatusLine = LBound(web_CurlResponseLines) To UBound(web_CurlResponseLines)
If VBA.Trim$(web_CurlResponseLines(web_FindStatusLine)) <> "" Then
If VBA.Split(web_CurlResponseLines(web_FindStatusLine), " ")(1) <> "100" Then
Exit Function
End If
End If
Next web_FindStatusLine
End Function
Private Function web_FindBlankLine(web_CurlResponseLines() As String) As Long
For web_FindBlankLine = (web_FindStatusLine(web_CurlResponseLines) + 1) To UBound(web_CurlResponseLines)
If VBA.Trim$(web_CurlResponseLines(web_FindBlankLine)) = "" Then
Exit Function
End If
Next web_FindBlankLine
End Function
Private Sub Class_Initialize()
web_CrLf = VBA.Chr$(13) & VBA.Chr$(10)
Set Headers = New Collection
Set Cookies = New Collection
End Sub