好吧,我很难过这个.
我最近在这里下载并安装了php的OAuth库:http://us3.php.net/manual/en/book.oauth.php
使用这个,我创建了一些测试代码,试图连接到我的Tumblr帐户并发帖.
我能够获得RequestToken和Authorize.但是当我提出实际请求时,我收到一个错误:
Invalid auth/bad request (got a 404, expected HTTP/1.1 20X or a redirect)
Run Code Online (Sandbox Code Playgroud)
我的请求网址格式正确为http://api.tumblr.com/v2/blog/account/post.我正在发出POST请求.所以我不确定为什么它会返回404.
这是我的代码:
<?php
$req_url = 'http://www.tumblr.com/oauth/request_token';
$authurl = 'http://www.tumblr.com/oauth/authorize';
$acc_url = 'http://www.tumblr.com/oauth/access_token';
$conskey = '123';
$conssec = '456';
session_start();
// In state=1 the next request should include an oauth_token.
// If it doesn't go back to 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
$oauth = new OAuth($conskey,$conssec);
$oauth->enableDebug();
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$request_token_info = $oauth->getRequestToken($req_url, 'http://www.domain.com/oauth.php');
$_SESSION['secret'] = $request_token_info['oauth_token_secret'];
$_SESSION['state'] = 1;
//Make authorize request with oauth_token
header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
exit;
} else if($_SESSION['state']==1) {
//Callback code
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
$access_token_info = $oauth->getAccessToken($acc_url);
$_SESSION['state'] = 2;
$_SESSION['token'] = $access_token_info['oauth_token'];
$_SESSION['secret'] = $access_token_info['oauth_token_secret'];
}
//Make tumblr post request
$oauth->setToken($_SESSION['token'],$_SESSION['secret']);
$oauth->fetch("http://api.tumblr.com/v2/blog/account/post", null, OAUTH_HTTP_METHOD_POST, array('type'=>'text', 'body'=>'this is a test')); //error happens here
$json = json_decode($oauth->getLastResponse());
print_r($json);
} catch(OAuthException $E) {
print_r($E);
}
?>
Run Code Online (Sandbox Code Playgroud)
非常感谢任何提示
我找到了答案.
问题在于:
$oauth->fetch("http://api.tumblr.com/v2/blog/account/post", null, OAUTH_HTTP_METHOD_POST, array('type'=>'text', 'body'=>'this is a test')); //error happens here
Run Code Online (Sandbox Code Playgroud)
首先,对于帐户,我只是拥有我的博客的名称.实际上,tumblr api中描述的base-hostname需要采用'blogname.tumblr.com'格式.不仅仅是'blogname',就像我拥有它一样.这将给出400.
其次,获取参数的顺序错误.正确的顺序是这样的:
string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]]
Run Code Online (Sandbox Code Playgroud)
哪个翻译到我的例子将...
$oauth->fetch("http://api.tumblr.com/v2/blog/blogname.tumblr.com/post", array('type'=>'text', 'body'=>'this is a test'), OAUTH_HTTP_METHOD_POST );
Run Code Online (Sandbox Code Playgroud)
我写了一个关于让它在这里工作的教程