现在我有一个有效的POC API,它根据产品ID返回产品。我可以使用Swagger成功测试API。我的VB6代码如下:
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方法中使用了类似的代码,并通过URL成功传递了参数,但我似乎无法使POST方法正常工作。我有一种感觉它位于xmlhttp.send方法中。
答案 0 :(得分:1)
通过重新格式化来实现:
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