使用 Oauth 和 Gdata 在 Java 中构建一个简单的应用程序

发布于 2024-11-14 23:29:00 字数 3747 浏览 3 评论 0原文

我正在尝试在用户登录的应用程序引擎上创建一个简单的应用程序 通过他们的 Google 帐户,然后将一个事件添加到他们的 日历。 为此,我将 Java 与 Eclipse 一起使用。我找到了一个简单的 在线代码:

public void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException { 
    // Create an instance of GoogleOAuthParameters 
    GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); 
    oauthParameters.setOAuthConsumerKey(CONSUMER_KEY); 
    oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET); 
    oauthParameters.setScope("http://docs.google.com/feeds/"); 
    GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper( 
            new OAuthHmacSha1Signer()); 
    // Remember the token secret that we stashed? Let's get it back 
    // now. We need to add it to oauthParameters 
    String oauthTokenSecret = (String) req.getSession().getAttribute( 
    "oauthTokenSecret"); 
    oauthParameters.setOAuthTokenSecret(oauthTokenSecret); 
    // The query string should contain the oauth token, so we can just 
    // pass the query string to our helper object to correctly 
    // parse and add the parameters to our instance of oauthParameters 
    oauthHelper.getOAuthParametersFromCallback(req.getQueryString(), 
            oauthParameters); 
    try { 
        // Now that we have all the OAuth parameters we need, we can 
        // generate an access token and access token secret. These 
        // are the values we want to keep around, as they are 
        // valid for all API calls in the future until a user revokes 
        // our access. 
        String accessToken = oauthHelper.getAccessToken(oauthParameters); 
        String accessTokenSecret = oauthParameters.getOAuthTokenSecret(); 
        // In a real application, we want to redirect the user to a new 
        // servlet that makes API calls. For the safe of clarity and simplicity, 
        // we'll just reuse this servlet for making API calls. 
        oauthParameters = new GoogleOAuthParameters(); 
        oauthParameters.setOAuthConsumerKey(CONSUMER_KEY); 
        oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET); 
        // This is interesting: we set the OAuth token and the token secret 
        // to the values extracted by oauthHelper earlier. These values are 
        // already in scope in this example code, but they can be populated 
        // from reading from the datastore or some other persistence mechanism. 
        oauthParameters.setOAuthToken(accessToken); 
        oauthParameters.setOAuthTokenSecret(accessTokenSecret); 
        oauthParameters.setOAuthCallback("http://www.facebook.com"); 
        oauthHelper.getUnauthorizedRequestToken(oauthParameters); 
        // Create an instance of the DocsService to make API calls 
        DocsService client = new DocsService("Malware Inc."); 
        // Use our newly built oauthParameters 
        client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer()); 
        URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full"); 
        DocumentListFeed resultFeed = client.getFeed(feedUrl, 
                DocumentListFeed.class); 
        for (DocumentListEntry entry : resultFeed.getEntries()) { 
            resp.getWriter().println(entry.getTitle().getPlainText()); 
        } 
    } catch (OAuthException e) { 
        // Something went wrong. Usually, you'll end up here if we have invalid 
        // oauth tokens 
        resp.getWriter().println("Here is the problem"); 
        //Server shows 500 problem 
    } catch (ServiceException e) { 
        // Handle this exception 
    } 
} 

我已经注册了我的应用程序并在上面添加了 KEY 和 Secret 该功能,但是当我将其部署到应用程序引擎时,它给出了 500 服务器错误。

有人可以发布一个使用 gdata 和 oauth 的简单 java 程序吗 登录 Google 用户并打印屏幕上的联系人? 谢谢。 -马诺伊

I am trying to create a simple app on the app engine where users log
in through their Google account, and then it adds an event to their
calendar.
And I am using Java along with Eclipse for this. I have found a simple
code online:

public void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException { 
    // Create an instance of GoogleOAuthParameters 
    GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters(); 
    oauthParameters.setOAuthConsumerKey(CONSUMER_KEY); 
    oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET); 
    oauthParameters.setScope("http://docs.google.com/feeds/"); 
    GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper( 
            new OAuthHmacSha1Signer()); 
    // Remember the token secret that we stashed? Let's get it back 
    // now. We need to add it to oauthParameters 
    String oauthTokenSecret = (String) req.getSession().getAttribute( 
    "oauthTokenSecret"); 
    oauthParameters.setOAuthTokenSecret(oauthTokenSecret); 
    // The query string should contain the oauth token, so we can just 
    // pass the query string to our helper object to correctly 
    // parse and add the parameters to our instance of oauthParameters 
    oauthHelper.getOAuthParametersFromCallback(req.getQueryString(), 
            oauthParameters); 
    try { 
        // Now that we have all the OAuth parameters we need, we can 
        // generate an access token and access token secret. These 
        // are the values we want to keep around, as they are 
        // valid for all API calls in the future until a user revokes 
        // our access. 
        String accessToken = oauthHelper.getAccessToken(oauthParameters); 
        String accessTokenSecret = oauthParameters.getOAuthTokenSecret(); 
        // In a real application, we want to redirect the user to a new 
        // servlet that makes API calls. For the safe of clarity and simplicity, 
        // we'll just reuse this servlet for making API calls. 
        oauthParameters = new GoogleOAuthParameters(); 
        oauthParameters.setOAuthConsumerKey(CONSUMER_KEY); 
        oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET); 
        // This is interesting: we set the OAuth token and the token secret 
        // to the values extracted by oauthHelper earlier. These values are 
        // already in scope in this example code, but they can be populated 
        // from reading from the datastore or some other persistence mechanism. 
        oauthParameters.setOAuthToken(accessToken); 
        oauthParameters.setOAuthTokenSecret(accessTokenSecret); 
        oauthParameters.setOAuthCallback("http://www.facebook.com"); 
        oauthHelper.getUnauthorizedRequestToken(oauthParameters); 
        // Create an instance of the DocsService to make API calls 
        DocsService client = new DocsService("Malware Inc."); 
        // Use our newly built oauthParameters 
        client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer()); 
        URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full"); 
        DocumentListFeed resultFeed = client.getFeed(feedUrl, 
                DocumentListFeed.class); 
        for (DocumentListEntry entry : resultFeed.getEntries()) { 
            resp.getWriter().println(entry.getTitle().getPlainText()); 
        } 
    } catch (OAuthException e) { 
        // Something went wrong. Usually, you'll end up here if we have invalid 
        // oauth tokens 
        resp.getWriter().println("Here is the problem"); 
        //Server shows 500 problem 
    } catch (ServiceException e) { 
        // Handle this exception 
    } 
} 

I have registered my application and added the KEY and Secret above
the function, but when I deploy it to the app engine it gives a 500
server error.

Could someone post a simple java program that uses gdata and oauth to
log in a Google user and print the contacts on the screen?
Thanks.
-Manoj

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

同展鸳鸯锦 2024-11-21 23:29:00

我面临着同样的问题,我花了一段时间才弄清楚。

实际上,问题在于您缺少 OAuth 授权过程中的某些部分。

如您所知,这是一个三足流程:

  1. 获取未经授权的请求令牌
  2. 授权请求令牌 将
  3. 授权的请求令牌交换为访问令牌,并用它调用 Google 数据。

就您而言,您将直接执行步骤 3。

因此,在调用上述 servlet 并有效检索用户的 Google 数据之前,
用户必须通过从其网络浏览器浏览授权 URL来授予对您的应用程序的访问权限

您需要第一个 servlet ,例如,在

        public void doGet(HttpServletRequest req, HttpServletResponse resp) {            

        GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();

        oauthParameters.setOAuthConsumerKey(YOUR_CONSUMER_KEY);
        oauthParameters.setOAuthConsumerSecret(YOUR_CONSUMER_SECRET);
        OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();

        GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
        oauthParameters.setScope(FEED_SCOPE);

        try {
            oauthHelper.getUnauthorizedRequestToken(oauthParameters);

            //GET THE UNAUTHORIZED TOKENS
            String oauthRequestToken = oauthParameters.getOAuthToken();
            String oauthTokenSecret = oauthParameters.getOAuthTokenSecret();

            //SAVE THEM SOMEWEHERE (FOR EXAMPLE IN THE SESSION LIKE YOU DID)

            //  ....

            //GET THE AUHTORIZATION URL
            String authorizationURL= oauthHelper.createUserAuthorizationUrl(oauthParameters);

            // YOU NOW HAVE THE AUHTORIZATION URL,  SEND IT BACK TO THE USER SOMEHOW
            // ( FOR EXAMPLE BY REDIRECTING THE REQUEST TO THAT URL)

            // ...
        } catch (OAuthException e1) {
            LOGGER.error("error while getting unauthorized request token '{}' ", e1);
        }
        }

用户导航后 可以通过 http://yourapp.com/RequestAccess 访问到该 URL 并授予访问权限,您现在可以调用第二个 servlet,它应该可以工作。

有关更多信息,请访问 Google OAuth 页面 此处

希望有帮助!

I was facing the same problem, and it took me a while to figure it out.

Actually, the problem is that your are missing some parts in the OAuth authorization process.

As you may know, it a 3-legged process:

  1. Get an unauthorized request token
  2. Authorize the request token
  3. Exchange the authorized request token for an access token and make calls to Google Data with it.

In your case, you are doing step 3 directly.

So before you can call the servlet you described above, and effectively retrieve user's Google Data,
the user must have grant access to your application, by browsing to an authorization URL from his web browser.

You need a first servlet , for example accessible at http://yourapp.com/RequestAccess

        public void doGet(HttpServletRequest req, HttpServletResponse resp) {            

        GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();

        oauthParameters.setOAuthConsumerKey(YOUR_CONSUMER_KEY);
        oauthParameters.setOAuthConsumerSecret(YOUR_CONSUMER_SECRET);
        OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();

        GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
        oauthParameters.setScope(FEED_SCOPE);

        try {
            oauthHelper.getUnauthorizedRequestToken(oauthParameters);

            //GET THE UNAUTHORIZED TOKENS
            String oauthRequestToken = oauthParameters.getOAuthToken();
            String oauthTokenSecret = oauthParameters.getOAuthTokenSecret();

            //SAVE THEM SOMEWEHERE (FOR EXAMPLE IN THE SESSION LIKE YOU DID)

            //  ....

            //GET THE AUHTORIZATION URL
            String authorizationURL= oauthHelper.createUserAuthorizationUrl(oauthParameters);

            // YOU NOW HAVE THE AUHTORIZATION URL,  SEND IT BACK TO THE USER SOMEHOW
            // ( FOR EXAMPLE BY REDIRECTING THE REQUEST TO THAT URL)

            // ...
        } catch (OAuthException e1) {
            LOGGER.error("error while getting unauthorized request token '{}' ", e1);
        }
        }

Once the user has navigate to that URL, and grant acces, you can now call your second servlet and it should work.

More info can be found on Google OAuth page here

Hope it helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文