3

我正在用 Perl 开发一个 web 应用程序,并尝试使用 OAuth2 在用户的 Google 日历中创建事件。身份验证和请求日历数据工作正常,我只是在发送 POST 请求并将 JSON 或哈希数据附加到它时完全卡住了。模块是否有为此提供的方法?该文档没有指向我这里的任何地方。我猜 LWP 会提供方法,但这似乎是很多开销。

到目前为止,这是我完成获取日历事件的方法(现在作为一个简单的控制台应用程序):

use Net::OAuth2::Profile::WebServer;

my $auth = Net::OAuth2::Profile::WebServer->new
    ( name           => 'Google Calendar'
    , client_id      => $id
    , client_secret  => $secret
    , site           => 'https://accounts.google.com'
    , scope          => 'https://www.googleapis.com/auth/calendar'
    , authorize_path    => '/o/oauth2/auth'
    , access_token_path => '/o/oauth2/token'
    , redirect_uri      => $redirect
    );

print $auth->authorize_response->as_string;
my $code=<STDIN>;

my $access_token = $auth->get_access_token($code);

my $response = $access_token->get('https://www.googleapis.com/calendar/v3/calendars/2j6r4iegh2u8o2409jk8k2g838@group.calendar.google.com/events');
  $response->is_success
      or die "error: " . $response->status_line;

print $response->decoded_content;

非常感谢您的时间!

马库斯

4

1 回答 1

0

我想是时候回答我自己的问题了。为了在 POST 请求中传输 JSON(创建日历事件),我最终使用了 LWP::UserAgent 和 HTTP::Request。为了设置内容类型,我首先必须创建一个 HTTP::Request-object 并设置标头和数据:

my $req = HTTP::Request->new( 'POST', 'https://www.googleapis.com/calendar/v3/calendars/<calendarID>/events' );
$req->header( 'Content-Type' => 'application/json' );
$req->content( "{ 'summary': 'EventName', 'start': { 'dateTime': '2015-02-11T20:48:00+01:00' }, 'end': { 'dateTime': '2015-02-11T22:30:00+01:00' } }" );

然后我创建了一个 LWP::UserAgent-object,将 OAuth2-token 附加到它并让它触发请求:

my $apiUA = LWP::UserAgent->new();
$apiUA->default_header(Authorization => 'Bearer ' . $access_token->access_token() );

my $apiResponse = $apiUA->request( $req );

就是这么简单。不过,使用 Net::OAuth2 将这一切合二为一会更好。

于 2015-02-12T17:46:38.257 回答