如何在php中使用Curl发布数据?
问题描述:
我已经在restler框架中创建了Web服务,并且我尝试使用curl从我创建的客户端库的php中插入数据.
I have created webservices in restler framework and I am trying to insert data using curl in php from client lib that I have created.
api.php
/**
* Manually routed method. we can specify as many routes as we want
*
* @url POST addcomment/{token}/{email}/{comment}/{story_id}
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
出于客户的测试目的:testing.php
for testing purpose from client : testing.php
$data_string = "token=900150983cd24fb0d6963f7d28e17f72&email=kamal@gmail.com&comment=commentusingcurl&story_id=2";
$ch = curl_init('http://localhost/Restler/public/examples/news/addcomment');
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 : text","Content-lenght:".strlen($data_string)));
$result = curl_exec($ch);
但抛出 404 .请帮忙.
答
您不应将所有参数映射到URL,
You should not be mapping all the parameters to URL,
/**
* Manually routed method. we can specify as many routes as we want
*
* @url POST addcomment/{token}/{email}/{comment}/{story_id}
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
这样做,API只能接受URL,例如
By doing so the API can only accept URL such as
http://localhost/Restler/public/examples/news/addcomment/900150983cd24fb0d6963f7d28e17f72/kamal@gmail.com/commentusingcurl/2
将您的API方法更改为
Change you API method to
/**
* Manually routed method. we can specify as many routes as we want
*
* @url POST addcomment
*/
function addComment($token,$email,$comment,$story_id){
return $this->dp->insertComment($token,$email,$comment,$story_id);
}
然后您的cURL示例应该可以正常工作
Then your cURL example should work fine
$data_string = "token=900150983cd24fb0d6963f7d28e17f72&email=kamal@gmail.com&comment=commentusingcurl&story_id=2";
$ch = curl_init('http://localhost/Restler/public/examples/news/addcomment');
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 : text","Content-lenght:".strlen($data_string)));
$result = curl_exec($ch);