2017-02-22 91 views
0

我有一個JSON字符串,我想使用POST將它傳遞給API。如何使用POST在CURL請求中傳遞JSON

當我嘗試傳遞數據時,我得到「JSON無效」。我使用API​​的內置測試工具手動測試了JSON字符串,並知道字符串的工作原理。該函數適用於使用GET從API中獲取。

我懷疑在使用POST時PHP/curl語法可能是錯誤的?

function curl($url = null,$method = null,$body = null){ 

    $loginauth = base64_encode('SECRETKEY'); 

    if($method == null){ 

     $method = 'GET'; 
     $headers = array(
      'Accept: application/hal+json,application/vnd.error+json', 
      'Authorization: Basic '.$loginauth 
     ); 

    }else{ 

     $method = 'POST'; 
     $headers = array(
      'Content-Type: application/json', 
      'Authorization: Basic '.$loginauth 
     ); 
    } 

    if($url == null){ 
     $url = 'https://coolapi.com/api/v1/companies'; 
    } 

    if($body == null){ 
     $body = ''; 
    } 

    $curl = curl_init(); 
    curl_setopt_array($curl, array(
     CURLOPT_SSL_VERIFYPEER => false, 
     CURLOPT_SSL_VERIFYHOST => false, 
     CURLOPT_RETURNTRANSFER => true, 
     CURLOPT_URL => $url, 
     CURLOPT_CUSTOMREQUEST => $method, 
     CURLOPT_HTTPHEADER => $headers, 
     CURLOPT_POSTFIELDS => $body 
    )); 

    $response = curl_exec($curl); 
    $err = curl_error($curl); 
    curl_close($curl); 

    if($err){ 
     return $err; 
    }else{ 
     return json_decode($response); 
    } 
} 

我的函數調用:

$url = 'https://one-url'; 
$data = '{ 
    "date": "2017-02-22", 
    "identifier": "1337", 
    "lines": [ 
    { 
     "test": "this is a test", 
    } 
    ], 
    "name": "Wolf" 
}'; 


$register_sale = curl(
    $url, 
    'POST', 
    $data 
); 
+0

哪裏是curlMe功能? – Naincy

+0

立即重命名功能。 – sdfgg45

回答

1

在PHP中,沒有預先定義的數據類型爲JSON,如果你傳遞JSON數據; PHP會認爲它是字符串。因此,使用json_encode聲明數組並將其轉換爲json,它將起作用。

試試看。

$data = [ 
    "date"=> "2017-02-22", 
    "identifier" => "1337", 
    "lines" => [ "test" => "this is a test" ], 
    "name"=> "Wolf" 
]; 
$json = json_encode($data); 

$register_sale = curl($url,'POST', $json); 

參考:https://lornajane.net/posts/2011/posting-json-data-with-php-curl

+0

仍然得到:壞JSON。位置:1:1,路徑:'' – sdfgg45

+0

現在它沒有給無效的JSON ....壞Json它的東西.... json中需要的一些值可能是你不發送 – Naincy

+0

在代碼中測試的字符串是相同的即時通訊測試使用api的testingtool,它的工作原理,這就是爲什麼我覺得它很奇怪。 – sdfgg45