我正在尝试使用curl使用php发布帖子请求但是json没有被传递到REST API。这是我的代码。在webservice中我获得的是null值。我不确定我哪里出错了。
$email_json_data = json_encode($email_data);
$header[] = "Content-type: application/json";
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $email_json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
网络服务代码:
$email_json_data = $this->post('email_json_data');
$email_data = json_decode($email_json_data);
答案 0 :(得分:0)
连接到服务器时可能存在问题,可能是您的$header
之一。要了解更多信息,您需要显示(在生产中,记录它)卷曲错误。
将来,请尝试添加完整的代码示例,而不仅仅是代码段
class CurlAdapter
{
private $api_url = 'www.somewhere.com/api/server.php';
private $error = "";
private function jsonPost($data)
{
// init curl
$ch = curl_init($this->api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl header
$header[] = "Content-type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// build post data
$post_data = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// execute
if (empty($response = curl_exec($ch)) {
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
$this->error = "cURL error ({$errno}):\n {$error_message}";
// @todo log curl error
}
}
// Close the handle
curl_close($ch);
return $response;
}
public function post( mixed $data )
{
if (empty($this->jsonPost($data))) {
return $this->error;
}
return $response;
}
}
$ca = new CurlAdapter();
echo $ca->post(['data' => 'testdata']);
答案 1 :(得分:0)
想出一种方法来完成这项工作。
替换为$email_json_data = $this->post('email_json_data');
$email_json_data = file_get_contents("php://input");