我试图通过他们的oauth2机制连接到deviantart。我确实得到了获取访问令牌的代码,但是当我试图通过file_get_contents获得访问令牌时,我得到了一些奇怪的404错误。但是,当我复制url时,我能够获得所需的访问令牌。这与标题设置有关吗?下面是获取访问令牌的代码:
function getAccessToken($code) {
$url = "https://www.deviantart.com/oauth2/token";
$data = array();
$data["grant_type"] = "authorization_code";
$data["client_id"] = $this->client_id;
$data["client_secret"] = $this->client_secret;
$data["redirect_uri"] = $this->redirect_uri;
$data["code"] = $code;
return $this->sendToDeviantArt($url, $data);
}
private function sendToDeviantArt($url=null, $data=array()) {
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded'r'n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
这花了我几个小时,但显然,deviantart想要有一个USER_AGENT集。因此,对于记录,这可以完美地工作(注意user_agent变量)
private function sendToDeviantArt($url=null, $data=array()) {
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded'r'n",
'method' => 'POST',
'content' => http_build_query($data),
'user_agent' => $_SERVER["HTTP_USER_AGENT"]
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
EDIT:为了记录,我们已经为一些deviantart函数编写了一个包装器,并在github上上传了一个小库。
这对我来说也是一种痛苦。感谢Jan对用户代理的提醒。我只是想提供一个卷曲的替代品,因为这是我正在使用的。显然编辑到你的内心内容,但如果你通过它传递一个deviantART api的url,这是有效的。
function curl($url) {
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the user agent
curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
return $result;
}
' ' '
获取访问令牌的示例用法:$json = json_decode(curl("https://www.deviantart.com/oauth2/token?response_type=code&client_id=0&client_secret=0&grant_type=client_credentials"), true);
$json["access_token"];