Code Servlet to Read/Write Google Sheets Data

2019-08-17 19:02发布

问题:

I'm writing a Servlet that reads and writes data in a Google Sheets doc. The doc is owned or shared with the account of the user hitting the Servlet, so they must authenticate using OAuth2.

I wrote a commandline (Java) application that works to get access using the Google API Client Library. I generated a client ID of Application Type "other". Then I wrapped that application in a Servlet extends HttpServlet (running in standalone Jetty). The flow stalls at

Credential credential =
    new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
    .authorize("user");

because the authorize() call outputs to STDERR (ie. Jetty log) the authorization URL and listens on a socket until it hears a valid authenticated/authorized token. Even if the Servlet could catch the auth URL from STDERR it couldn't send it back to the user for clicking, because 1> it's stalled at authorize() and 2> it can send back only a single HTML response.

I'm trying to follow Google's documentation Google API Client Libraries Java / Web server applications, but the supplied code is for Calendar and the doc doesn't explain how to use it in a Servlet (or in anything else). That doc also links to a Google Identity Platform / Using OAuth 2.0 for Web Server Applications doc, but it starts off offering to document a Java project then provides code and guidance only for PHP, Python, Ruby, HTTP/REST. There are bits and pieces of guidance in blogs, other Google docs, other products, other OAuth2 targets, across many versions of the Google API and of OAuth - incomprehensible.

Where can I find good docs of the implementation procedure, especially with sample code? An example project? Or just directions for porting the commandline application to a Servlet? Thank you.