You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Visual Basic发送带请求体的GET请求调用RESTful API

Visual Basic调用RESTful JSON接口实现

现有逻辑说明

当前接口逻辑及可正常运行的参考信息如下:

  • 后端为AWS Lambda服务,接收JSON格式请求体,读取email_address字段做授权校验,返回Authorised或NotAuthorised字符串结果
  • 可正常运行的Python调用示例:
import requests
x = requests.request(method='get', url='APIURL', data='{"email_address":"a@hotmail.com"}')
x.json()
  • 后端Lambda实现参考:
import boto3
import json

users = ["a@hotmail.com", "b@hotmail.com"]

def respond(res):
    return {
        'statusCode': 200,
        'body': json.dumps(res),
        'headers': {
            'Content-Type': 'application/json'
        }
    }

def lambda_handler(event, context):
    body = event['body'] 
    email_address = json.loads(body)['email_address']
    if email_address in users:
        response = "Authorised"
        return respond(response)
    else:
        response = "NotAuthorised"
        return respond(response)

可直接运行的Visual Basic实现

以下代码兼容VBA(Office宏、WPS宏、Access等场景)、VB6,依赖系统内置组件,无需额外安装依赖:

Sub CallAuthorizationAPI()
    Dim httpRequest As Object
    Dim apiEndpoint As String
    Dim jsonRequestBody As String
    Dim apiResponse As String
    
    ' 替换为你实际的API访问地址
    apiEndpoint = "替换为你的APIURL"
    ' 构造和Python示例完全一致的JSON请求体,VB中双引号需要用两个双引号转义
    jsonRequestBody = "{""email_address"":""a@hotmail.com""}"
    
    ' 初始化HTTP请求对象
    Set httpRequest = CreateObject("MSXML2.XMLHTTP")
    ' 对应Python的GET请求方法,False表示同步等待接口返回
    httpRequest.Open "GET", apiEndpoint, False
    ' 设置请求头,声明发送内容为JSON格式
    httpRequest.setRequestHeader "Content-Type", "application/json"
    ' 携带请求体发送请求
    httpRequest.Send jsonRequestBody
    
    ' 读取接口返回结果,等价于Python中获取响应内容
    apiResponse = httpRequest.responseText
    
    ' 结果处理示例,可根据自身需求修改
    ' VBA环境下可在立即窗口查看返回结果
    Debug.Print "接口返回结果:" & apiResponse
    MsgBox "接口返回结果:" & apiResponse
    
    ' 释放对象资源
    Set httpRequest = Nothing
End Sub

注意事项

  • 如果使用VB.NET开发,仅需将HTTP客户端替换为.NET内置的HttpClient类即可,核心参数保持一致:请求方法为GET、Content-Type请求头设为application/json、请求体为格式正确的JSON字符串
  • 构造JSON请求体时注意转义规则,VB字符串中表示双引号需要写两个连续双引号,避免JSON格式错误导致接口解析失败
  • 若返回NotAuthorised,先检查传入的邮箱地址是否和授权列表完全匹配,确认无多余空格、大小写差异

内容的提问来源于stack exchange,提问作者Nalhcal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 05:12:27