使用php curl发出post请求时发出

使用php curl发出post请求时发出,php,json,curl,Php,Json,Curl,我试图使用curl使用php发出post请求,但是json没有被传递到RESTAPI。这是我的密码。在webservice中,我得到的只是空值。我不确定我错在哪里 $email_json_data = json_encode($email_data); $header[] = "Content-type: application/json"; $ch = curl_init($api_url); curl_setopt($ch, CURLOPT_POST, t

我试图使用curl使用php发出post请求,但是json没有被传递到RESTAPI。这是我的密码。在webservice中,我得到的只是空值。我不确定我错在哪里

    $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);
检查 连接到服务器时可能出现问题,可能是在您的
$header
中。要了解更多信息,您需要显示(在生产中,记录)curl错误

以后,请尝试包含完整的代码示例,而不仅仅是代码片段

从中添加的代码
找到了一个让这一切顺利的方法

替换了
$email\u json\u data=$this->post('email\u json\u data')

使用
$email\u json\u data=file\u get\u contents(“php://input");

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']);