我有一個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
);
哪裏是curlMe功能? – Naincy
立即重命名功能。 – sdfgg45