【随手记】PHP中Curl模拟请求Form-Data类型接口
warning:
这篇文章距离上次修改已过283天,其中的内容可能已经有所变动。
<?php
// 初始化一个 cURL 会话
$ch = curl_init();
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, "http://example.com/api/endpoint"); // 要请求的URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将curl_exec()获取的信息以字符串返回,而不是直接输出
curl_setopt($ch, CURLOPT_POST, true); // 发起POST请求
// 准备表单数据
$data = array('key1' => 'value1', 'key2' => 'value2');
// 构建正确的表单数据
$data_string = http_build_query($data);
// 设置请求头
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: ' . strlen($data_string))
);
// 提供数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
// 执行cURL会话
$response = curl_exec($ch);
// 关闭cURL资源,并释放系统资源
curl_close($ch);
// 打印结果
echo $response;
?>
这段代码演示了如何使用PHP cURL函数来模拟发送一个POST请求,其中包含表单数据类型(application/x-www-form-urlencoded)。它设置了请求的URL、返回结果的格式、POST字段和请求头。
评论已关闭