我目前正在努力做到这一点:
my $ua = Mojo::UserAgent->new;
my $req = Mojo::Message::Request->new;
my $tx = $ua->build_tx(GET => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full');
app->log->info($c->session('token'));
$tx->req->headers->authorization('Bearer ' . $c->session('token'));
其中$c->session('token')
是我通过Mojolicious::Plugin::OAuth2获得的令牌。
我只回复一个空洞的回复。通过curl做同样的事情(我认为)可以正常工作:
curl -v -H "authorization: Bearer the_same_token_as_above" https://spreadsheets.google.com/feeds/spreadsheets/private/full
我做错了什么?
答案 0 :(得分:2)
我唯一看到你遗失的是call to start
。将以下两行添加到您的代码块对我来说(虽然使用不同的url / token):
$tx = $ua->start($tx);
app->log->info($tx->res->body);
如果您需要授权许多API调用,那么您可能需要尝试similar to this方法,如下所示:
my $ua = Mojo::UserAgent->new;
$ua->on(start => sub {
my ($ua, $tx) = @_;
$tx->req->headers->authorization('Bearer <your token here>');
});
my $tx = $ua->get('<your first url here>');
app->log->info("Response body:", $tx->res->body);
my $tx = $ua->get('<your second url here>');
app->log->info("Response body:", $tx->res->body);
# etc...
这种技术的优点是每次使用get
实例的UserAgent
方法时,它都会触发启动事件监听器并为您添加授权标头。