将JSON对象作为POST请求发送 [英] Sending JSON object as a POST request

查看:852
本文介绍了将JSON对象作为POST请求发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Excel中的VBA应用程序发送JSON对象.下面的代码正确发送了请求,但是我无法弄清楚如何使用正文中的JSON对象发出请求.

I'm trying to send a JSON object from a VBA application in Excel. The code below sends the request correctly, however I can't figure out how to make the request with the JSON object in the body.

Sub Post()

    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "http://localhost:3000/test"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-type", "application/x-www-form-      urlencoded"
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("test=6")

End Sub

例如,如果我尝试发送"{test:6,test2:7}"并将请求的正文记录在服务器上,则会得到{'{parts:6,test:7}':''}

If I try for instance to send "{test:6, test2: 7}" and log the body of the request on the server I get { '{parts:6, test: 7}': '' }

推荐答案

您可能已经知道,JSON结构确实会引起严重的麻烦.就您而言,如果要验证您的{test:6, test2: 7}.

As you probably already know, JSON structure can really produce serious headaches. In your case, I would say its all about the quotes, as you can see in here if you try to validate your {test:6, test2: 7}.

尝试以下代码.对我来说似乎很合理:

Try the following code. It looks plausible to me:

Sub Post()

Dim URL As String, JSONString As String, objHTTP as Object

    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "http://localhost:3000/test"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-type", "application/x-www-form-      urlencoded"
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"

    JSONString = "{""test"": 6,""test2"":7}"

    objHTTP.Send JSONString

End Sub

这篇关于将JSON对象作为POST请求发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆