如何将终端curl API请求转换为PHP可执行的curl代码?
回答
现有转换逻辑存在问题,核心错误如下:
- 请求体格式不匹配:官方curl示例指定了
Content-Type: application/json,提交的是JSON格式字符串,但你参考的PHP代码直接将数组传给CURLOPT_POSTFIELDS,会默认把请求头改成application/x-www-form-urlencoded,提交表单格式数据,不符合API要求,会请求失败。 - 缺失必要请求头:官方示例要求的
Authorization鉴权头,你当前的参考代码没有配置,也没有显式声明JSON格式的Content-Type。
正确的原生PHP cURL实现(对应官方示例)
<?php // 替换为实际的接口地址和鉴权token $apiUrl = '你的实际接口前缀/api/rest/issues/'; $token = '你的实际鉴权token'; // 构造请求参数 $params = [ 'summary' => 'This is a test issue', 'description' => 'This is a test description', 'category' => [ 'name' => 'General' ], 'project' => [ 'name' => 'project1' ] ]; // 转成JSON字符串 $postJson = json_encode($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 对应curl命令的--location参数,自动跟随重定向 curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postJson); // 设置请求头 curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: ' . $token, 'Content-Type: application/json' ]); // 超时设置可按需求调整 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt($ch, CURLOPT_TIMEOUT, 30); $response = curl_exec($ch); // 可选:添加错误判断逻辑 if(curl_errno($ch)) { $error_msg = curl_error($ch); // 自行处理错误场景 } curl_close($ch); echo $response; ?>
更简洁的实现方式
你可以把cURL请求的通用逻辑封装为公共函数,后续调用时只需要传入必要参数即可,和原生curl命令一样简洁:
<?php // 封装公共POST JSON请求函数 function http_post_json($url, $token, $data) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: ' . $token, 'Content-Type: application/json' ]); $res = curl_exec($ch); curl_close($ch); return $res; } // 实际调用仅需一行代码 $response = http_post_json('你的接口地址', '你的token', $params); ?>
如果项目允许引入第三方HTTP客户端,代码可以进一步简化,上述原生封装方案不需要额外依赖,已经能满足简洁性需求。
内容的提问来源于stack exchange,提问作者user2399035
相关产品推荐
相关产品推荐

