用于在HTTP POST中传递参数的语法请求
问题描述:
现在我有一个可用的POC API,它返回基于产品ID的产品。我可以使用Swagger成功测试API。我的VB6的代码如下:用于在HTTP POST中传递参数的语法请求
Public Function WebRequestPost(sUrl As String) As String
Dim xmlhttp As MSXML2.xmlhttp
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST", sUrl, False
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlhttp.send "{""id"":2}"
WebRequestPost = xmlhttp.responseText
Set xmlhttp = Nothing
End Function
Private Sub Command2_Click()
Dim result As String
Dim url As String
Dim productId As String
url = "http://localhost:1112/api/Products"
result = WebRequestPost(url)
MsgBox result
End Sub
我已经使用了类似的代码与GET方法并传递参数通过与成功的网址,但我似乎无法得到POST方法的工作。我有一种感觉,它存在于xmlhttp.send方法中。
答
它的工作通过格式化:
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
到
xmlhttp.setRequestHeader "Content-Type", "application/json"
并通过有效载荷的形式:xmlhttp.send 2
被做成传递到一个变量参数形式为xmlhttp.send sId
与最终结束了:
Public Function WebRequestPost(sUrl As String, sId As Integer) As String
Dim xmlhttp As MSXML2.xmlhttp
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST", sUrl, False
xmlhttp.setRequestHeader "Content-Type", "application/json"
xmlhttp.send sId
WebRequestPost = xmlhttp.responseText
Set xmlhttp = Nothing
End Function
Private Sub Command2_Click()
Dim result As String
Dim url As String
Dim productId As String
url = "http://localhost:1112/api/products"
result = WebRequestPost(url, 3)
MsgBox result
End Sub
问题不是'send'但你要发送的内容。 – Bob77