使用PHP调用Azure DevOps API创建发布管道时遇类型转换错误
问题分析与修复方案
核心问题
- 请求体格式错误:你已经手动编写了JSON字符串
$body,却额外调用json_encode($body),导致原本的JSON被再次编码为转义后的字符串,Azure DevOps无法将其解析为ReleaseStartMetadata类型。 - 认证格式错误:Azure DevOps的Basic认证要求将
{空用户名}:{PAT}拼接后做Base64编码,而非直接使用原始PAT。 - 冗余Header参数:
api-version已在URL中指定,无需在请求Header重复添加。
修复后的代码
<?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $pat = 'hidden'; // 处理Basic认证:空用户名+PAT,拼接后Base64编码 $auth = base64_encode(":{$pat}"); $url = 'https://vsrm.dev.azure.com/org-id/workspace-name/_apis/release/releases?api-version=6.0'; // 用数组构造请求体再转JSON,避免手动写JSON的语法错误 $body = [ "definitionId" => 1, "description" => "test", "name" => "test", "isDraft" => false, "reason" => "manual" ]; $data_json = json_encode($body); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); // 修正Header,移除冗余参数,使用正确认证头 curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json; charset=utf-8', "Authorization: Basic {$auth}" ]); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); // 检查curl请求是否出错 if(curl_errno($ch)){ echo 'Curl错误:' . curl_error($ch); } $data = json_decode($response, true); print_r($data); curl_close($ch); ?>
额外说明
- 用数组构造请求体再转JSON,能避免手动编写JSON时的引号转义、语法遗漏等问题。
- 若问题仍存在,可打印
$data_json查看实际发送的请求体,对比Postman中的正确JSON是否一致。
内容的提问来源于stack exchange,提问作者user2965052
相关产品推荐
相关产品推荐

