如何通过php在两个服务器之间发送和接收JSON数据


How to send and receive JSON data between two servers via php

很明显,我在搜索中没有使用正确的关键词,或者不理解其他人在博客或论坛等中写的内容。

查找有关在两个服务器之间传递数据的信息。数据最好包含在JSON数组中。如果你知道有人写了一篇包含这一点的博客,我真的很想有机会读一读。否则你能提供一些想法吗?

更详细:当用户访问一个页面时,将调用一个PHP函数,一些数据将被"打包"到JSON数组中,然后向另一个服务器发送POST命令。接收POST后的第二个服务器将进行一些处理,然后"打包"一些数据并将其返回到JSON数组中。然后将向用户显示结果。

下面是我收到的HTTP 200响应。只是没有数据。

站点1:

$data_string = json_encode(array('user_id'=>123));
$ch = curl_init('http://site2.dev/retrieve');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string)
        ));
$result = curl_exec($ch);
$status = curl_getinfo($ch);
curl_close($ch);
$result = json_decode($result); 

站点2:

public function retrieve() {
    return json_encode(array('some'=>'456'));
}

选择Json数组是因为它可以加密,是的,HTTPS将在最终环境中使用。

这两台服务器都将使用Laravel 4作为PHP框架。

感谢您的想法和评论。

添加此项:

curl_setopt($ch, CURLOPT_HEADER, 0);

并在内容长度上加引号:

curl_setopt($ch, CURLOPT_HTTPHEADER,
    array('Content-Type: application/json','"Content-Length: ' . strlen($data_string) . '"'));