简体   繁体   English

如何在 VB.NET 中使用类似的 VBA 代码?

[英]How can I use the similar VBA code in VB.NET?

I have this code which makes an http request and returns the result in VBA (Excel).我有这段代码发出 http 请求并在 VBA (Excel) 中返回结果。 Does anyone know how to do similar in VB.NET?有谁知道如何在 VB.NET 中做类似的事情?

Sub GetRequest()

    MYURL = "xxx"
    Accesstoken = "xxx"

    'Send Request and get JSON Response
    Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")
    xmlhttp.Open "GET", myurl, False
    xmlhttp.setRequestHeader "Authorization", "Bearer " & AccessToken
    xmlhttp.Send
    JsonResponse = xmlhttp.responseText
    Debug.Print xmlhttp.responseText
    
    'Parse JSON
    Set Json = JsonConverter.ParseJSON(JsonResponse)
    Debug.Print xmlhttp.responseText

    Set xmlhttp = Nothing


End Sub

I'm new to VB.NET and mainly only use Excel VBA.我是 VB.NET 的新手,主要只使用 Excel VBA。

To send/receive HTTP requests/responses, typically you would use the HttpClient class ( documentation ).要发送/接收 HTTP 请求/响应,通常您会使用 HttpClient class( 文档)。 Specifically in this case you would:特别是在这种情况下,您将:

  1. Call the GetAsync method ( documentation ) to submit the request调用 GetAsync 方法( 文档)提交请求
  2. Check the response's StatusCode ( documentation ) to verify that a successful response was returned (presumably an OK - 200 status)检查响应的 StatusCode( 文档)以验证是否返回了成功的响应(可能是 OK - 200 状态)
  3. If a successful response was returned, get the response's Content ( documentation )如果返回成功响应,则获取响应的内容( 文档

Here is a function (untested) that should get you going in the right direction:这是一个 function (未经测试),它应该让你朝着正确的方向前进:

Imports System.Net
Imports System.Net.Http
Imports System.Threading.Tasks
Imports System.Text
'...
Private Async Function SendGet(url As String) As Task(Of String)
    Dim body = String.Empty
    Using client = New HttpClient
        Dim response = Await client.GetAsync(url)

        If (response.StatusCode = HttpStatusCode.OK) Then
            body = Await response.Content.ReadAsStringAsync()
        End If
    End Using
    Return body
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM