我尝试使用Content-Type=form-data对服务器发出post请求。这是在VB6中(是的,Visual basic6(。 请求调用成功,但服务器无法获取参数。
我正在用 httpbin.org 进行测试,最简单的。
Dim msxml As msxml.XMLHTTPRequest
Dim data As String
Dim boundary As String
Set msxml = New msxml.XMLHTTPRequest
boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
msxml.Open "POST", "http://httpbin.org/post", False
msxml.setRequestHeader "Content-Type", "multipart/form-data;Charset=UTF-8; boundary=" & boundary
data = ""
data = data & boundary & vbCrLf
data = data & "Content-Disposition: form-data; name=""param1""" & vbCrLf
data = data & vbCrLf
data = data & "data for param1" & vbCrLf
data = data & boundary & vbCrLf
data = data & "Content-Disposition: form-data; name=""param2""" & vbCrLf
data = data & vbCrLf
data = data & "other data for param2" & vbCrLf
data = data & boundary & "--"
msxml.Send data
Debug.Print msxml.responseText
获得的响应是:
{
"args": {},
"data": "",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "es",
"Cache-Control": "no-cache",
"Connection": "close",
"Content-Length": "216",
"Content-Type": "multipart/form-data;Charset=UTF-8; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"Host": "httpbin.org",
"User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0E)"
},
"json": null,
"origin": "181.45.250.169",
"url": "http://httpbin.org/post"
}
如您所见,"form">属性为空。
预期响应:
"form": {
"param1": "data for param1",
"param2": "other data for param2"
},
我已经尝试过WinHttpRequest和其他方法,结果总是相同的。
有什么建议吗?
更改如何:
boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
自:
boundary = "WebKitFormBoundary7MA4YWxkTrZu0gW"
。相反,然后在需要的地方,将此值前缀为"--"(而不是"----"(。
"--"前缀不属于这里,您连续有两个:
msxml.setRequestHeader "Content-Type", "multipart/form-data;Charset=UTF-8; boundary=" & boundary
通过加倍的"--",你似乎混淆了自己。 连字符不是边界值的一部分。
在此行之后
data = data & "other data for param2" & vbCrLf
在此行之前
msxml.Send data
尝试推杆
data = data & boundary & "--"
以语法上有效的方式结束窗体的主体。
感谢所有帮助过我的人。
除了向我建议的边界错误之外,我尝试过但没有成功的事情,因为我缺少参数的内容类型。
添加内容类型和正确的边界字符串,帖子有效
Dim msxml As msxml.XMLHTTPRequest
Dim data As String
Dim boundary As String
Set msxml = New msxml.XMLHTTPRequest
boundary = "MyCustomBoundary7MA4YWxkTrZu0gW"
msxml.Open "POST", "http://httpbin.org/post", False
msxml.setRequestHeader "Content-Type", "multipart/form-data;Charset=UTF-8; boundary=" & boundary
data = ""
data = data & "--" & boundary & vbCrLf
data = data & "Content-Disposition: form-data; name=""param1""" & vbCrLf
data = data & "Content-Type: text/plain" & vbCrLf & vbCrLf
data = data & "data for param1" & vbCrLf
data = data & "--" & boundary & vbCrLf
data = data & "Content-Disposition: form-data; name=""param2""" & vbCrLf
data = data & "Content-Type: text/plain" & vbCrLf & vbCrLf
data = data & "other data for param2" & vbCrLf
data = data & "--" & boundary & "--"
msxml.Send data
Debug.Print msxml.responseText