如何使用PHP Curl发送POST请求提交数组数据到指定接口
PHP发送POST请求实现方案
目标:将指定数组数据发送到接口 https://exam.nocortech.com/api/create-task
方案1:cURL扩展实现(推荐)
cURL是PHP中最常用的HTTP请求工具,兼容性好,支持丰富的配置项,代码如下:
<?php // 待提交的原始数据 $data = array( "exam_no" => 'EX-A20210001', "uid" => array('9a7f0d289c66ce63','c7f660212bb6d5cb'), "start_time" => '2021-05-07 16:50:00', "end_time" => '2021-05-07 17:30:00', "company_id" => '14' ); $apiUrl = 'https://exam.nocortech.com/api/create-task'; // 初始化cURL $ch = curl_init(); // 设置请求地址 curl_setopt($ch, CURLOPT_URL, $apiUrl); // 标记为POST请求 curl_setopt($ch, CURLOPT_POST, true); // 提交数据:如果接口要求传JSON格式,就把$data转json:json_encode($data),同时修改下面的Content-Type为application/json curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 设置返回结果不直接输出 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 测试环境可跳过SSL证书校验,正式环境建议关闭做合规校验 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 设置请求头,默认form表单格式提交 curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded' // 'Content-Type: application/json' // JSON格式提交时打开该注释,关闭上行配置 )); // 执行请求,获取返回结果 $response = curl_exec($ch); // 捕获请求错误 if(curl_errno($ch)){ $error = curl_error($ch); // 可自定义错误处理逻辑,比如打印日志、抛出异常 var_dump('请求错误:'.$error); } // 关闭cURL资源 curl_close($ch); // 处理返回结果,接口一般返回JSON格式,可转数组后续处理 $responseData = json_decode($response, true); var_dump($responseData); ?>
方案2:file_get_contents实现(适配无cURL扩展的环境)
如果服务器未开启cURL扩展,可以用PHP内置的文件操作函数实现POST请求,代码如下:
<?php // 待提交的原始数据 $data = array( "exam_no" => 'EX-A20210001', "uid" => array('9a7f0d289c66ce63','c7f660212bb6d5cb'), "start_time" => '2021-05-07 16:50:00', "end_time" => '2021-05-07 17:30:00', "company_id" => '14' ); $apiUrl = 'https://exam.nocortech.com/api/create-task'; // 构造请求参数:form表单格式用http_build_query,JSON格式直接json_encode($data) $postData = http_build_query($data); // $postData = json_encode($data); // JSON格式提交时打开该注释,关闭上行配置 $context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded' . "\r\n" . // 'header' => 'Content-Type: application/json' . "\r\n" . // JSON格式提交时打开该注释,关闭上行配置 'Content-Length: ' . strlen($postData) . "\r\n", 'content' => $postData, 'timeout' => 10, // 请求超时时间,单位秒 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false ) ) )); // 发送请求获取返回结果 $response = file_get_contents($apiUrl, false, $context); // 处理返回结果 $responseData = json_decode($response, true); var_dump($responseData); ?>
注意事项
- 可以根据接口要求的参数格式,对照代码注释调整提交格式和请求头
- 正式线上环境建议移除跳过SSL校验的配置,避免安全风险
- 可根据业务需求自行修改错误处理、返回结果解析的逻辑
内容的提问来源于stack exchange,提问作者Question Maker
相关产品推荐
相关产品推荐

