0

上网找了几天,一直没找到用php发布数据的好例子,我下载了http_pecl,试了一下

你能帮我理解我的代码有什么问题吗?我相信是我发送的数据错误,因此服务器看不到它(服务器期望数据的方式与 jquery post 发送的方式相同)

$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);
  }
});
4

1 回答 1

0

你可以用 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);

希望这有帮助!

于 2013-11-12T17:43:35.357 回答