I am posting data from Vb.net client to a PHP rest api but for some reason the json_decode is not working on the passed string.
The code to post to the server is :
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()
The values that are being passed :
{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }
On the PHP side I do :
$bookings = $_POST->bookings
$data = json_decode($bookings,true);
$total = count($data['booking']);
The $total should show 1 as there is 1 item in the booking array but it always is shows 0
$_POST->bookings - this is your problem. -> is the object access operator, but in PHP, $_POST is not an object but an array.
If you were submitting this value as part of form data, you would normally access it via array syntax (e.g. $_POST['bookings']), but from your VB code, you're actually posting the JSON string as the POST body itself.
In PHP, you can access the raw POST body like this:
$bookings = file_get_contents('php://input');
The rest of your code should then work as usual.
Edit: actually, you've got a typo in there as well. Try
$total = count($data['bookings']);
// or
$total = count($data['bookings']['booking']);
There is a json array there also. Try this.
<?php
$data='{"key":"91a1522Test",
"bookings":
{"booking":[{"ClassId":"4", "ClassName":"THOASC", "YearWeek":"1751"}]} }';
$data = json_decode($data,true);
echo '<pre>';
print_r($data);
$total = count($data['bookings']['booking']);
echo $total;
$data = json_decode($bookings,true);
Here as per the php documentation sencond argument in json_decode function denotes whether return output as an object or as an array
argument 2 = true ( will return array )
argument 2 = false ( will return object , it is the default value)
The json_decode produces the following array
Array
(
[key] => 91a1522Test
[bookings] => Array
(
[booking] => Array
(
[0] => Array
(
[ClassId] => 4
[ClassName] => THOASC
[YearWeek] => 1751
)
)
)
)
Hence it should be accessed like count($data['bookings']['booking'])
Related
i have a device that send POST data to my server.
so print_r($_POST) is empty, i can see the data only when i run this
$content = file_get_contents('php://input');
var_dump($content);
//or i can use: print_r($content);
i save those to a file and result are some json and BINARY DATA (CHECK IMAGE)
if i add code like this json_decode($content,true); i dont see anything
so how can i decode binary or what can i do to decode the json and also see what data is send in binary?
If you want to decode binary data inPHP, try the following:
<?php
$binarydata = "\x04\x00\xa0\x00";
$data = unpack('C*', $binarydata);
var_dump($data);
output:
array (size=4)
1 => int 4
2 => int 0
3 => int 160
4 => int 0
Load your contents from file_get_contents('php://input') to $binarydata and you will get an array of values. You can then apply some logic to extract JSON string and process it.
private void timer1_Tick(object sender, System.EventArgs e)
{
int iIdx;
int[] iData;
bool[] bData;
if (m_bRegister) // Read registers (4X references)
{
// read register (4X) data from slave
if (adamTCP.Modbus().ReadHoldingRegs(m_iStart, m_iLength, out iData))
{
m_iCount++; // increment the reading counter
txtStatus.Text = "Read registers " + m_iCount.ToString() + " times...";
// update ListView
label1.Text = HttpGet("http://127.0.0.1/misc/api1.php?value0=" + iData[0].ToString());
label2.Text = HttpGet("http://127.0.0.1/misc/api1.php?value1=" + iData[1].ToString());
label3.Text = HttpGet("http://127.0.0.1/misc/api1.php?value2=" + iData[2].ToString());
label4.Text = HttpGet("http://127.0.0.1/misc/api1.php?value3=" + iData[3].ToString());
label5.Text = HttpGet("http://127.0.0.1/misc/api1.php?value4=" + iData[4].ToString());
for (iIdx = 0; iIdx < m_iLength; iIdx++)
{
listViewModbusCur.Items[iIdx].SubItems[2].Text = iData[iIdx].ToString(); // show value in decimal
listViewModbusCur.Items[iIdx].SubItems[3].Text = iData[iIdx].ToString("X04"); // show value in hexdecimal
}
How do i send array using httpget method? The code on top show that i'm sending data one by one. I need to send it in array and retrieve it back in api,php so that i could insert it into database in one row. currently, it's 1 data for 1 row.
Here is a example to convert array to json in PHP
$arr=array(
"varl1"=>1,
"varl2"=>"example",
"varl3"=>3,
);
$json_arr=json_encode($arr);
Now you can send $json_arr
and then you can decode it using json_decode()
you should passing 'value0' become just one querystring, ex : value[]
so the url will become
http://127.0.0.1/misc/api1.php?value[]="+ iData[0].ToString()"&value[]="+ iData[1].ToString() and etc what you want to send it "
or you should use http_build_query to the param array data
the code you show is php ??
the api maybe php but the code style more like .NET c#
correct me if im wrong.
//Update Response
string[] param = new string[(how many your counter param)];
param [0] = "test0";
param [1] = "test1";
param [2] = "test2";
in my example i give you 3
string sParams = JsonConvert.SerializeObject(param) ;
HttpGet("http://127.0.0.1/misc/api1.php?value=" + sParams);
I'm trying to send data from a VB.NET Application to a php application, i found this code:
Private Function SendRequest(uri As Uri, jsonDataBytes As Byte(),contentType As String, method As String) As String
Dim req As WebRequest = WebRequest.Create(uri)
req.ContentType = contentType
req.Method = method
req.ContentLength = jsonDataBytes.Length
Dim stream = req.GetRequestStream()
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
stream.Close()
Dim response = req.GetResponse().GetResponseStream()
Dim reader As New StreamReader(response)
Dim res = reader.ReadToEnd()
reader.Close()
response.Close()
Return res
End Function
Dim data = Encoding.UTF8.GetBytes(jsonSring)
Dim result_post = SendRequest(uri, data, "application/json", "POST")
at: source
But I can't get the posted data on php. It sends the headers, but the data no.
So, I need help to figure it out what is missing.
I also had same issue and got solution from comments only. As you are passing binary data then in php you need to read binary data as raw input
To get the Raw Post Data:
<?php $postdata = file_get_contents("php://input"); ?>
I found a code for how to send a post to php but i can send only one variable.
Here is my code:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim postData = "msg=" & TextBox2.Text
Dim request As WebRequest = WebRequest.Create("http://localhost/msg.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
End Sub
If you read some documentation on how post works, you will find that each key/value pair has to be separated by a &.
Dim postData = "msg=" & TextBox2.Text & "&msg2=" & TestBox3.Text
You still need to make sure your value are properly encoded.
Dim postData = "msg=" & TextBox2.Text & "&msg2=" & TestBox3.Text
This statement will still be considered as a single array. (NOT two different values)
or you can say different values in single string.
I guess in order to send multiple values, we must have to use array with (key->value) combination.
where Key = msg and value will betextbox1.text and so on.
I'm sending a string to a php script and trying to make a jsonarray out of it for processing and putting it into an sql table. I send a string from an android application to the server:
[{"name":"bob","datetime":"2012-04-14 10:40"},{"name":"Anonymous","datetime":"2012-04-14 10:40"}]
I used http://jsonlint.com/ to validate the jsonarray and it is valid. When I have the following php script:
<?php
$json_as = stripslashes($_POST["json_a"]);
//$out.=json_decode(jsoninfo);
$realjson = json_decode($json_as, true);
//print $json_as;
//echo $realjson[name];
//print $realjson[name];
print $json_as;
?>
I see get the following info in my LogCat:
The Response text is [{"name":"bob","datetime":"2012-04-14 10:40"},{"name":"Anonymous","datetime":"2012-04-14 10:40"}]
I've been trying to use this for reference without luck: http://webhole.net/2009/08/31/how-to-read-json-data-with-php/
But when I try to change the php script to pring something out from the variable $realjson, nothing comes back. How do I get the information out of the json string I am sending?
Here is complete tutorial to send and recieve JSON data between PHP and Android.
I hope this can help you.
Query:
http://localhost/testJson.php?data=[{%22name%22:%22bob%22,%22datetime%22:%222012--04-14%2010:40%22},{%22name%22:%22Anonymous%22,%22datetime%22:%222012-04-14%2010:40%22}]
PHP CODE :
COde :
<?php
$data = $_REQUEST['data'];
print_r(json_decode($data));
?>
Result :
Array ( [0] => stdClass Object ( [name] => bob [datetime] =>
2012--04-14 10:40 ) 1 => stdClass Object ( [name] => Anonymous
[datetime] => 2012-04-14 10:40 ) )
Sent a string in JSON format, then used the following code:
$json_as = stripslashes($_POST["json_a"]);
trim($json_as, "[");
trim($json_as, "]");
$realjson = json_decode($json_as, true);
//$uses = "name";
mysql_select_db("thoughtsdata",$con);
foreach($realjson as $item) {
$name = $item[name];
$datetime = $item[datetime];
//processed code
}