基于https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28我有这个代码:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/repos/octocat/Hello-World/commits");
$headers = [
'Accept: application/vnd.github+json',
'Authorization: Bearer <my personal token>',
'X-GitHub-Api-Version: 2022-11-28'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec($ch);
curl_close($ch);
print $server_output ;
但它不返回任何东西。是白页。如果我直接在浏览器中访问 url,我就能看到 API 的响应。
我做错了什么?
GitHub 要求你发送一个
User-Agent
:
行政法规禁止的要求。 请确保您的请求具有 User-Agent 标头 (https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required)。
显然 PHP 的
curl
模块不会自动发送一个。通过手动设置
User-Agent
标题
$headers = [
…
'User-Agent: curl'
];
或
curl_setopt($ch, CURLOPT_USERAGENT, "curl");
对我有用。
简化的工作示例:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/repos/octocat/Hello-World/commits");
curl_setopt($ch, CURLOPT_USERAGENT, "curl");
curl_exec($ch);
curl_close($ch);