# [](#vba-web)VBA-Web
VBA-Web(以前稱為Excel-REST)使得在Windows和Mac上使用VBA輕松處理復雜的Web服務和API。 它包括對身份驗證的支持,自動轉換和解析JSON,使用cookie和標頭等等。
[](https://www.patreon.com/timhall)
## [](#getting-started)入門
* 下載 [最新版 (v4.1.6)](https://github.com/VBA-tools/VBA-Web/releases)
* 安裝或更新現有文件使用 `VBA-Web - Installer.xlsm`
* 要在Excel中從頭開始,`VBA-Web - Blank.xlsm`已經完成了所有設置并準備就緒
更多信息請查看 [Wiki](https://github.com/VBA-tools/VBA-Web/wiki)
## [](#upgrading)升級
要從Excel-REST升級到VBA-Web,參照[升級指南](https://github.com/VBA-tools/VBA-Web/wiki/Upgrading-from-v3-to-v4)
注意:在解析Mac的解析器問題時,已暫時從VBA-Web中刪除XML支持。 Windows上仍然可以支持XML,參照[這些說明](https://github.com/VBA-tools/VBA-Web/wiki/XML-Support-in-4.0)使用自定義格式化程序。
## [](#notes)說明
* 內置身份驗證支持,支持HTTP Basic,OAuth 1.0,OAuth 2.0,Windows,Digest,Google等。 有關更多信息,請參閱 [授權](Authentication.md)
* 對于代理環境,`Client.EnabledAutoProxy = True`將自動加載代理設置
* 支持自定義請求和響應格式。 請參閱[RegisterConverter](RegisterConverter.md)
## [](#examples)范例
以下示例演示如何使用Google Maps API獲取兩個位置之間的路線。
### [](#getjson-example)GetJSON Example
~~~vbnet
Function GetDirections(Origin As String, Destination As String) As String
'// 創建WebClient以執行請求
'// 并設置一個基本URL,將所有請求附加到
Dim MapsClient As New WebClient
MapsClient.BaseUrl = "https://maps.googleapis.com/maps/api/"
'// 使用GetJSON幫助程序執行簡單請求并使用響應
Dim Resource As String
Dim Response As WebResponse
Resource = "directions/json?" & _
"origin=" & Origin & _
"&destination=" & Destination & _
"&sensor=false"
Set Response = MapsClient.GetJSON(Resource)
'// => GET https://maps.../api/directions/json?origin=...&destination=...&sensor=false
ProcessDirections Response
End Function
Public Sub ProcessDirections(Response As WebResponse)
If Response.StatusCode = WebStatusCode.Ok Then
Dim Route As Dictionary
Set Route = Response.Data("routes")(1)("legs")(1)
Debug.Print "It will take " & Route("duration")("text") & _
" to travel " & Route("distance")("text") & _
" from " & Route("start_address") & _
" to " & Route("end_address")
Else
Debug.Print "Error: " & Response.Content
End If
End Sub
~~~
VBA-Web中有3個主要組件:
1. `WebRequest` 用于定義復雜請求
2. `WebClient` 用于執行請求
3. `WebResponse` 用于處理回應
在上面的例子中,請求相當簡單,因此我們可以跳過創建一個`WebRequest`,而是使用`Client.GetJSON`幫助器來從特定的URL獲取json。 在處理響應時,我們可以查看`StatusCode`以確保請求成功,然后使用`Data`參數中的解析json從響應中提取復雜信息。
### [](#webrequest-example)WebRequest范例
如果您希望對請求有更多控制權,則以下示例使用“WebRequest”來定義復雜請求。
~~~vbnet
Function GetDirections(Origin As String, Destination As String) As String
Dim MapsClient As New WebClient
MapsClient.BaseUrl = "https://maps.googleapis.com/maps/api/"
'// 創建WebRequest以獲取路線
Dim DirectionsRequest As New WebRequest
DirectionsRequest.Resource = "directions/{format}"
DirectionsRequest.Method = WebMethod.HttpGet
'// 設置請求格式
'// -> 設置content-type和accept 標頭并解析響應
DirectionsRequest.Format = WebFormat.Json
'// 替換{format} 段
DirectionsRequest.AddUrlSegment "format", "json"
'// 添加querystring到request
DirectionsRequest.AddQuerystringParam "origin", Origin
DirectionsRequest.AddQuerystringParam "destination", Destination
DirectionsRequest.AddQuerystringParam "sensor", "false"
'// => GET https://maps.../api/directions/json?origin=...&destination=...&sensor=false
'// 執行請求并使用響應
Dim Response As WebResponse
Set Response = MapsClient.Execute(DirectionsRequest)
ProcessDirections Response
End Function
Public Sub ProcessDirections(Response As WebResponse)
'// ... 與前面的示例相同
End Sub
~~~
上面的例子演示了`WebRequest`提供的一些強大功能。 一些功能包括:
* Url segments (用值替換資源中的{segment})
* Method (GET, POST, PUT, PATCH, DELETE)
* content-type、accept headers、轉換/解析請求和響應的格式(json,xml,url編碼,純文本)
* QuerystringParams
* Body
* Cookies
* Headers
更多內容, 查閱文檔的[`WebRequest`](WebRequest.md)部分
### [](#authentication-example)Authentication 范例
以下示例演示如何使用帶有VBA-Web的身份驗證器來查詢Twitter, `TwitterAuthenticator`(在`authenticators /`[文件夾](https://github.com/VBA-tools/VBA-Web/tree/master/authenticators)中找到)使用Twitter的OAuth 1.0a身份驗證及其詳細信息 創建可以在[Wiki](https://github.com/VBA-tools/VBA-Web/wiki/Implementing-your-own-IAuthenticator)中[實現自己的IWebAuthenticator](%E5%AE%9E%E7%8E%B0%E8%87%AA%E5%B7%B1%E7%9A%84IWebAuthenticator.md)找到。
~~~vbnet
Function QueryTwitter(Query As String) As WebResponse
Dim TwitterClient As New WebClient
TwitterClient.BaseUrl = "https://api.twitter.com/1.1/"
' Setup authenticator
Dim TwitterAuth As New TwitterAuthenticator
TwitterAuth.Setup _
ConsumerKey:="Your consumer key", _
ConsumerSecret:="Your consumer secret"
Set TwitterClient.Authenticator = TwitterAuth
' Setup query request
Dim Request As New WebRequest
Request.Resource = "search/tweets.json"
Request.Format = WebFormat.Json
Request.Method = WebMethod.HttpGet
Request.AddQuerystringParam "q", Query
Request.AddQuerystringParam "lang", "en"
Request.AddQuerystringParam "count", 20
'// => GET https://api.twitter.com/1.1/search/tweets.json?q=...&lang=en&count=20
'// 授權承載令牌...(自動接收并添加到Twitter身份驗證器)
Set QueryTwitter = TwitterClient.Execute(Request)
End Function
~~~
更多信息, 查閱 [Wiki](https://github.com/VBA-tools/VBA-Web/wiki), [文檔](https://vba-tools.github.com/VBA-Web/docs/), 和[范例](Examples.md)
### [](#release-notes)Release Notes
View the [changelog](https://github.com/VBA-tools/VBA-Web/blob/master/CHANGELOG.md) for release notes
### [](#about)About
* Author: Tim Hall
* License: MIT
* 機翻搬運工:gnefnuy
- README
- 指南
- 概述
- GET Request
- WebRequest
- 屬性
- Resource
- Method
- Body
- Format
- RequestFormat
- ResponseFormat
- CustomRequestFormat
- CustomResponseFormat
- ContentType
- Accept
- ContentLength
- FormattedResource
- Cookies
- Headers
- QuerystringParams
- UrlSegments
- 方法
- AddHeader
- SetHeader
- AddUrlSegment
- AddQuerystringParam
- AddCookie
- AddBodyParameter
- CreateFromOptions
- WebClient
- 屬性
- BaseUrl
- Authenticator
- TimeoutMs
- ProxyServer
- ProxyBypassList
- ProxyUsername
- ProxyPassword
- EnableAutoProxy
- Insecure
- FollowRedirects
- 方法
- Execute
- GetJson
- PostJson
- SetProxy
- GetFullUrl
- WebResponse
- 屬性
- StatusCode
- StatusDescription
- Content
- Data
- Body
- Headers
- Cookies
- 方法
- Update
- WebHelpers
- 屬性
- WebStatusCode
- WebMethod
- WebFormat
- UrlEncodingMode
- EnableLogging
- 方法
- LogDebug
- LogWarning
- LogError
- LogRequest
- LogResponse
- Obfuscate
- ParseJson
- ConvertToJson
- ParseUrlEncoded
- ConvertToUrlEncoded
- ParseXml
- ConvertToXml
- ParseByFormat
- ConvertToFormat
- UrlEncode
- UrlDecode
- Base64Encode
- Base64Decode
- RegisterConverter
- JoinUrl
- UrlParts
- CloneDictionary
- CloneCollection
- CreateKeyValue
- FindInKeyValues
- AddOrReplaceInKeyValues
- FormatToMediaType
- MethodToName
- HMACSHA1
- HMACSHA256
- MD5
- CreateNonce
- IWebAuthenticator
- 方法
- BeforeExecute
- AfterExecute
- PrepareHttp
- PrepareCurl
- WebAsyncWrapper
- 屬性
- Client
- 方法
- ExecuteAsync
- 范例
- Salesforce網站
- Google APIs
- Todoist API
- 其他主題
- 調試
- 授權
- 實現自己的IWebAuthenticator
- Url編碼