[英]How to determine if posting JSON with PHP cURL is succeed?
我想知道我是否成功地将我的 JSON 发布到这个 url http://localhost/api_v2/url/post?key=***
,所以我最终可以检索它们,但我不确定,我将如何测试它们.
通常,我们可以只用print_r($result )
来查看变量中的内容,但是当我这样做时,什么也没有显示出来。
当我做echo $result
也没有出现。
到目前为止,没有任何帮助,所以我决定要向上移动的下一个变量$ch
当我echo $ch;
我得到了这个Resource id #188
。 现在,我被困住了。
有人可以帮我澄清一下吗?
public function post(){
$ch = curl_init("http://localhost/api_v2/url?key=***");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$file_name = 'inventory.csv';
$file_path = 'C:\\QuickBooks\\'.$file_name;
$csv= file_get_contents($file_path);
$utf8_csv = utf8_encode($csv);
$array = array_map("str_getcsv", explode("\n", $utf8_csv));
$json = json_encode($array, JSON_PRETTY_PRINT);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($status == 200){
echo "Post Successfully!";
}
}
这是我的路线
// API Version 2
Route::group(array('prefix' => 'api_v2'), function(){
Route::post('url/post', array('before' => 'api_v2', 'uses' => 'UrlController@post'));
Route::get('url/reveive', array('before' => 'api_v2', 'uses' => 'UrlController@receive'));
Route::get('url/store', array('before' => 'api_v2', 'uses' => 'UrlController@store'));
});
我建议您使用返回的 HTTP 状态码来确定请求是否成功:
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($status == 200){
echo "Post Successfully!";
}
我还认为有些事情不太正确,因为dd($result)
显示了一个 404 页面。 可能没有路由匹配POST http://localhost/api_v2/url?key=***
我不是 curl 专家,但据我所知,您应该将该数据作为数组传递:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' => $json));
在另一端,您可以像这样检索它:
$data = json_decode(Input::get('data'));
要在单个路由上使用 CSRF 过滤器:
Route::post('url/post', array('before' => 'csrf|api_v2', 'uses' => 'UrlController@post'));
或者对某个 HTTP 动词使用 CSRF(如果需要,还可以使用前缀)
Route::when('*', 'csrf', array('post'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.