我将数据从Vb.net客户端发布到PHP rest api但由于某种原因json_decode不能处理传递的字符串.
发布到服务器的代码是:
Dim payload As String = "{""key"":""Test"",""bookings"":" & txtUpload.Text & "}"
Dim request As WebRequest = WebRequest.Create(String.Format(baseAPIImportUrl))
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim byteArray() As Byte = Encoding.UTF8.GetBytes(payload)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse
' display the status.
MessageBox.Show(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream
' Open the stream using a StreamReader for easy access.
Dim reader As StreamReader = New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd
' display the content.
' Console.WriteLine(responseFromServer)
MessageBox.Show(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
正在传递的值:
{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }
在PHP方面,我做:
$bookings = $_POST->bookings
$data = json_decode($bookings,true);
$total = count($data['booking']);
$total应该显示1,因为预订数组中有1个项目,但总是显示0
解决方法:
$_POST->预订 – 这是你的问题. – >是对象访问操作符,但在PHP中,$_POST不是对象而是数组.
如果您将此值作为表单数据的一部分提交,您通常会通过数组语法访问它(例如$_POST [‘bookings’]),但是从VB代码中,您实际上是将JSON字符串作为POST主体本身发布.
在PHP中,您可以像这样访问原始POST主体:
$bookings = file_get_contents('PHP://input');
然后你的其余代码应该像往常一样工作.
编辑:实际上,你也有一个错字.尝试
$total = count($data['bookings']);
// or
$total = count($data['bookings']['booking']);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。