PHP Curl调用Microsoft Graph API含单引号Filter报400错误求助
解决PHP cURL请求Microsoft Graph带单引号Filter的Bad Request问题
用
http_build_query自动处理参数编码
手动拼接URL容易出现编码遗漏,用PHP内置的http_build_query构建查询参数,它会严格按照RFC3986标准编码所有特殊字符,包括单引号。示例代码:$startDate = '2022-10-01T12:30:00'; $endDate = '2022-11-01T12:30:00'; $params = [ 'filter' => "start/dateTime ge '$startDate' and end/dateTime lt '$endDate'" ]; $query = http_build_query($params, '', '&', PHP_QUERY_RFC3986); $url = "https://graph.microsoft.com/v1.0/groups/12345/events?$query";单独编码Filter中的单引号
单引号在URL中对应的编码是%27,可以直接替换Filter字符串里的单引号,避免编码工具的过度处理。示例:$filter = str_replace("'", "%27", "start/dateTime ge '2022-10-01T12:30:00' and end/dateTime lt '2022-11-01T12:30:00'"); $url = "https://graph.microsoft.com/v1.0/groups/12345/events?filter=$filter";检查cURL请求头与调试输出
确保请求头包含正确的Authorization和Content-Type,同时开启cURL调试模式查看实际发送的URL,对比Graph Explorer的请求内容找差异:$ch = curl_init($url); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer YOUR_ACCESS_TOKEN', 'Content-Type: application/json' ]); // 开启调试 curl_setopt($ch, CURLOPT_VERBOSE, true); $verboseLog = fopen('php://temp', 'w+'); curl_setopt($ch, CURLOPT_STDERR, $verboseLog); // 执行请求 $response = curl_exec($ch); // 读取调试信息 rewind($verboseLog); echo stream_get_contents($verboseLog);改用POST请求的批量查询方式
如果GET请求的编码问题始终无法解决,可以用Microsoft Graph的批量查询功能,将Filter参数放在POST请求体中:$batchData = [ 'requests' => [ [ 'id' => '1', 'method' => 'GET', 'url' => '/groups/12345/events?filter=start/dateTime ge \'2022-10-01T12:30:00\' and end/dateTime lt \'2022-11-01T12:30:00\'' ] ] ]; $ch = curl_init('https://graph.microsoft.com/v1.0/$batch'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($batchData)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer YOUR_ACCESS_TOKEN', 'Content-Type: application/json' ]); $response = curl_exec($ch);
内容的提问来源于stack exchange,提问作者Jordan
相关产品推荐
相关产品推荐

