PHP用CURL发送Content-type为application/json的POST请求方法

247 阅读1分钟

在PHP中,我们可以使用cURL库来发送Content-type为application/json的POST请求。以下是一个示例代码:

// 准备数据
$data = array(
    "key1" => "value1",
    "key2" => "value2"
);
$jsonData = json_encode($data);

// 初始化cURL会话
$ch = curl_init('http://www.example.com/api');

// 设置cURL选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData))
);

// 执行cURL请求
$result = curl_exec($ch);

// 关闭cURL会话
curl_close($ch);

在这段代码中,我们首先创建了一个包含我们要发送的数据的数组,并使用 json_encode函数将其转换为JSON格式。然后,我们初始化了一个cURL会话,并设置了一些选项,包括POST请求方法、要发送的数据、返回结果和HTTP头部信息。最后,我们执行了cURL请求并关闭了会话。


香港五网CN2网络云服务器链接:www.tsyvps.com

蓝易云香港五网CN2 GIA/GT精品网络服务器。拒绝绕路,拒绝不稳定。