php - 通过 CURL 发布 JSON 数据并抓取它

标签 php json curl

我正在尝试将 json 数据作为参数传递给 cURL POST。但是,我坚持捕获它并将其保存在数据库上。

curl 文件:

$data = array("name" => "Hagrid", "age" => "36");                                                                    
$data_string = json_encode($data);                                                                                   

$url = 'http://localhost/project/test_curl';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
                                    'Content-Type: application/json')                                                                                           
                                    );                       
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                                                     

$result = curl_exec($ch);  

//based on http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl

test_curl 文件:

    $order_info = $_POST; // this seems to not returning anything

    //SAVE TO DB... saving empty...

我错过了什么?呜....

最佳答案

您在正文中将数据作为原始 JSON 发送,它不会填充 $_POST 变量。

您需要做以下两件事之一:

  1. 您可以将内容类型更改为将填充$_POST 数组的类型
  2. 您可以阅读原始 body 数据。

如果您可以控制通信的两端,我会推荐选项二,因为它将请求正文大小保持在最低限度并随着时间的推移节省带宽。 (编辑:我在这里并没有真正强调它将节省的带宽量可以忽略不计,每个请求只有几个字节,这只在非常高流量的环境中才是有效的关注点。但是我仍然推荐选项二因为这是最干净的方式)

在您的 test_curl 文件中,执行以下操作:

$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);

$postedJson = json_decode($rawData);

var_dump($postedJson);

如果要填充 $_POST 变量,您需要更改将数据发送到服务器的方式:

$data = array (
  'name' => 'Hagrid',
  'age' => '36'
);

$bodyData = array (
  'json' => json_encode($data)
);
$bodyStr = http_build_query($bodyData);

$url = 'http://localhost/project/test_curl';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/x-www-form-urlencoded',
  'Content-Length: '.strlen($bodyStr)
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr);

$result = curl_exec($ch);

原始的、未解码的 JSON 现在将在 $_POST['json'] 中可用。

关于php - 通过 CURL 发布 JSON 数据并抓取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9062060/

相关文章:

php - Codeigniter 链式查询问题

json - 类型错误 : <object> is not JSON serializable

java - 在控制台上以 json 格式打印 Final Class

php - 如何从 PHP 中的 301 重定向下载链接获取图像?

php - 通过 HTTP 而不是 SSL 发送的 Cookie

php - 如何加入表格 Codeigniter

ios - 如何在 ios Swift 中将 JSON 转换为字符串?

networking - Ambari 1.6.1 hadoop端口8088没有网站

由 C++ libcurl json rest

PHP - Join 语句重复记录