[英]Passing JSON through cURL POST PHP
我一直在嘗試使用cURL通過我的Web應用程序傳遞JSON-現在有點卡住了。
這是我嘗試過的:
第1步:
我試圖使用此發布 JSON
<?php
public function post(){
$cars = array("Volvo", "BMW", "Toyota");
$json = json_encode($cars);
$ch = curl_init("http://localhost/api_v2/url?key=***");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('json' => $json));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
}
?>
第2步:
我試圖使用這個來接收 JSON
public function get(){
$json = json_decode(Input::get('json'));
dd($json); // null
}
結果: -當我做
dd($json);
時,我一直得到nulldd($json);
有人可以幫我指出我做錯了什么嗎?
詳細說明:
我還確定JSON不會損壞,因為添加了print("<h1> JSON </h1><pre>".print_r($json,true)."</pre><br><hr><br>");
我可以看到JSON正常顯示。
見圖片
至於調試工作,您應該轉儲響應,而不是json_decode
嘗試解析它。
所以改變這個
public function get() {
$json = json_decode(Input::get('json'));
dd($json); // null
}
對此
public function get() {
dd(Input::get('json'));
}
那應該更好地幫助您找到實際的問題,最有可能的是服務器沒有使用有效的JSON進行響應。
另一個選擇是使用json_last_error
查看為什么響應不可解析。
public function get() {
$json = json_decode(Input::get('json'));
// If the response was parseable, return it
if($json !== null)
return $json;
// Determine if the response was a valid null or
// why it was unparseable
switch (json_last_error()) {
// The server could respond with a valid null,
// so go ahead and return it.
case JSON_ERROR_NONE:
return $json;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
}
看起來您沒有返回cURL調用的結果。
public function post()
{
// The first part of your original function is fine...
$response = curl_exec($ch);
curl_close($ch);
// But you need to return the response!
return $response;
}
如果客戶端是腳本(即不是瀏覽器),則無法在服務器端打印內容。
您在服務器端打印的所有內容都將返回給客戶端(post()腳本)。
話雖如此,您的json應該出現在$response
變量中。 您可以輸出。 但這不是調試api請求的最佳方法。
更簡單的方法是刪除dd()並寫入日志文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.