Home > Backend Development > PHP Tutorial > php中curl模拟post发送json并接收json

php中curl模拟post发送json并接收json

WBOY
Release: 2016-06-06 20:35:34
Original
1379 people have browsed it

具体描述:
本地模拟请求服务器数据,请求数据格式为json,服务器返回数据也是json。
使用ajax模拟都成功了

<script> $.ajax({ type: "POST", crossDomain: true, url: 'http://*******', data: {'command':'test'}, success: function(e) { console.log(e);//这里log的是json }, dataType: 'json' }); </script>

curl就没有成功
$url = 'http://*******';
$param = "{'command':'test'}";
$ch = curl_init($url); //请求的URL地址
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);//$data JSON类型字符串
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($param)));
$data = curl_exec($ch);//这里的data打印出来是空的

回复内容:

具体描述:
本地模拟请求服务器数据,请求数据格式为json,服务器返回数据也是json。
使用ajax模拟都成功了

<script> $.ajax({ type: "POST", crossDomain: true, url: 'http://*******', data: {'command':'test'}, success: function(e) { console.log(e);//这里log的是json }, dataType: 'json' }); </script>

curl就没有成功
$url = 'http://*******';
$param = "{'command':'test'}";
$ch = curl_init($url); //请求的URL地址
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);//$data JSON类型字符串
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($param)));
$data = curl_exec($ch);//这里的data打印出来是空的

$param = "{'command':'test'}";
这一行改成PHP数组键值的形式。
因为curl模拟POST的时候,POST的参数应该是以数组的形式传参。

请问lz最后的代码是怎么写的,我把param换成数组,最后获取数据也是空

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template