我已经在网上找了几天,但找不到使用 php 发布数据的好例子,我下载了http_pecl并尝试使用它
你能帮我了解我的代码有什么问题吗?我相信是我发送了错误的数据,所以服务器看不到它(服务器期望数据与jquery帖子发送数据的方式)
$headers = array('method' => 'POST','Content-type' => 'application/json','content'=>json_encode(array('api_key'=>'5675476','grant_type' => 'password', 'username' => '12345','password'=>'12345')));
$r = new HttpRequest('http:/zztestapi.com/api/v5/authorize?api_key=5675476&grant_type=password&username=12345&password=12345', HttpRequest::METH_POST);
$r->setHeaders($headers);
$r->setContentType = 'application/json';
//$r->setBody(json_encode(array('api_key'=>'5675476','grant_type' => 'password', 'username' => '12345','password'=>'password')));
//$r->addPostFields(array('api_key'=>'5675476','grant_type' => 'password', 'username' => '12345','password'=>'password'));
//$r->addRawPostData(json_encode(array('api_key'=>'9000000141','grant_type' => 'password', 'username' => '12345','password'=>'password')));
$r->setOptions(array('cookies' => array('lang' => 'de')));
echo $r->send()->getBody();
$r->send();
我的目标是获得类似于jquery帖子的代码
$.ajax({
url: 'http://zztestapi.com/api/v5/authorize',
type: 'POST',
data: {"api_key":"5675476","grant_type":"password","username":"12345","password":"12345"},
dataType: 'application/json',
success: function(data) {
alert(data);
}
});
你可以用cURL来做到这一点,下面是这个例子:
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('http://api.local/rest/users');
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);
希望这有帮助!