要通过 PHP 发送 POST 请求,需要设置请求头
时间: 2024-04-01 08:37:03 浏览: 10
发送 POST 请求时,可以设置请求头来指定请求的一些参数,比如 Content-Type、Authorization 等。下面是使用 curl 发送 POST 请求并设置请求头的示例代码:
```php
$url = 'http://example.com/api';
$data = array(
'param1' => 'value1',
'param2' => 'value2'
);
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer xxxxxxxx'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 处理响应内容
```
在上面的代码中,$headers 是请求头数组,使用 curl_setopt 函数设置 CURLOPT_HTTPHEADER 选项可以将请求头设置到 curl 请求中。需要注意的是,请求头数组中每个元素都必须是一个字符串,格式为 "Header-Name: Header-Value"。