头图

使用PHP的CURL库发送Content-type为application/json的POST请求可以通过以下方法实现:

  1. 初始化CURL:使用 curl_init()函数来初始化一个CURL会话。
$ch = curl_init();
  1. 设置CURL选项:使用 curl_setopt()函数设置各种选项。这包括设置URL、POST请求、POST数据和HTTP头信息。
curl_setopt($ch, CURLOPT_URL, "http://example.com/api");  // 设置URL
curl_setopt($ch, CURLOPT_POST, 1);  // 设置为POST请求
  1. 设置POST数据:POST数据应该是一个JSON字符串,可以使用 json_encode()函数将数组转换为JSON字符串。
$data = array("key1" => "value1", "key2" => "value2");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));  // 设置POST数据
  1. 设置HTTP头:设置Content-type为application/json。
$headers = array(
    'Content-Type: application/json',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);  // 设置HTTP头
  1. 执行CURL请求:使用 curl_exec()函数执行CURL请求,并获取结果。
$result = curl_exec($ch);
  1. 关闭CURL会话:使用 curl_close()函数关闭CURL会话。
curl_close($ch);

以上就是使用PHP的CURL库发送Content-type为application/json的POST请求的方法。


蓝易云
36 声望4 粉丝