2 回答

TA貢獻1836條經驗 獲得超4個贊
我嘗試在php中使用curl訪問相同的URL,它似乎工作正常。請查看以下示例:
<form method="post">
<input type="text" name="username">
<button>Submit</button>
</form>
<?php
if (!empty($_POST["username"])) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/users/".$_POST["username"]);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
}
?>

TA貢獻1811條經驗 獲得超6個贊
按原樣運行該腳本將返回有關用戶代理的錯誤消息:
行政法規禁止的請求。請確保您的請求具有用戶代理標頭(http://developer.github.com/v3/#user-agent-required)。檢查 https://developer.github.com 以了解其他可能的原因。
來自該站點:“所有 API 請求都必須包含有效的用戶代理標頭。沒有用戶代理標頭的請求將被拒絕。"
因此,要將用戶代理標頭添加到 cURL 請求中,請將代碼更改為
<?php
if (!empty($_POST["username"])) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/users/".$_POST["username"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Oussama Mater Test-App'); // line added
$output=curl_exec($ch);
print_r($output);
curl_close($ch);
} else {
echo "No POST username";
}
使用表單完成代碼:
<form method="post">
<input type="text" name="username">
<button>Submit</button>
</form>
<?php
if (!empty($_POST["username"])) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/users/" . $_POST["username"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Oussama Mater Test-App');
$output=curl_exec($ch);
print_r($output);
curl_close($ch);
}
- 2 回答
- 0 關注
- 300 瀏覽
添加回答
舉報