我将数据从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()
Run Code Online (Sandbox Code Playgroud)
正在传递的值:
{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }
Run Code Online (Sandbox Code Playgroud)
在PHP方面,我做:
$bookings = $_POST->bookings
$data = json_decode($bookings,true);
$total = count($data['booking']);
Run Code Online (Sandbox Code Playgroud)
$ total应该显示1,因为预订数组中有1个项目,但总是显示0
$_POST->bookings- 这是你的问题.->是对象访问运算符,但在PHP中,$_POST不是对象而是数组.
如果您将此值作为表单数据的一部分提交,通常可以通过数组语法(例如$_POST['bookings'])访问它,但是从VB代码中,您实际上是将JSON字符串作为POST正文发布.
在PHP中,您可以像这样访问原始POST主体:
$bookings = file_get_contents('php://input');
Run Code Online (Sandbox Code Playgroud)
然后你的其余代码应该像往常一样工作.
编辑:实际上,你也有一个错字.尝试
$total = count($data['bookings']);
// or
$total = count($data['bookings']['booking']);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |