通过VBA从URL下载Json Obeject

时间:2016-06-07 21:31:45

标签: json vba ms-access url

我有一个MS Access项目,需要我从URL检索和解析Json对象。我已经完成了解析部分,但我无法弄清楚从URL中检索Json的正确方法。如果我在IE上复制并粘贴URL,它将自动将Json对象下载为.json文件。我搜索过谷歌的解决方案,但这些都不适合我。我认为问题是URL看起来像" https://******.com/rest/external/session/123" ;,这与标准的XML HTTP请求URL不相似。所以大多数使用XMLHTTP请求的解决方案对我来说都不起作用。

我尝试使用以下代码从URL获取它。但我得到的只是主页DOM树而不是Json。

Dim wb As XMLHTTP
 Set wb = New XMLHTTP
 wb.Open "POST", "https://******.com/rest/external/session/123", False
 wb.send
 Do Until wb.Status = 200 And wb.ReadyState = 4
   DoEvents
 Loop
 Debug.Print wb.responseText

任何人都知道我应该在这做什么? 任何帮助表示赞赏!

更新:

  1. 我已尝试过POST和GET http请求。它给了我相同的结果

  2. 以下是fiddler捕获的进程。

  3. This is captured processes if I copy the url directly on IE

    This is captured processes if I use the code above

1 个答案:

答案 0 :(得分:0)

只是解释下面的代码逻辑。您需要使用它来构建自己的代码。

Option Compare Database

Dim ApiUrl As String
Dim reader As New XMLHTTP60
Dim coll As Collection
Dim Json As New clsJSONParser

Public Sub ApiInitalisation()
    ApiUrl = "http://private-anon-73376961e-count.apiary-mock.com/"
End Sub

Public Sub GetPerson()
On Error GoTo cmdLogIn_Click_Err

'For API
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim contact As Variant

Api.ApiInitalisation
ApiUrl = ApiUrl & "users/5428a72c86abcdee98b7e359"

reader.Open "GET", ApiUrl, False
'reader.setRequestHeader "Accept", "application/json"
reader.send

'Temporay variable to store the response
Dim egTran As String

' Add data to Table
If reader.Status = 200 Then
    Set db = CurrentDb
    Set rs = db.OpenRecordset("tblPerson", dbOpenDynaset, dbSeeChanges)

    egTran = "[" & reader.responseText & "]"
    Set coll = Json.parse(egTran)

    For Each contact In coll
        rs.AddNew
        rs!FName = contact.Item("name")
        rs!Mobile = contact.Item("phoneNumber")
        rs!UserID = contact.Item("deviceId")
        rs!SID = contact.Item("_id")
        rs.Update
    Next

Else
    MsgBox "Unable to import data."
End If

End Sub