使用google-calendar-api和OAuth2与java web app

时间:2015-01-23 15:10:48

标签: java http java-ee web-applications google-api

我试图在java网络应用程序中使用google-calendar-api:

首先我知道我需要向谷歌发送请求获取授权令牌。我有这个网址:

https://accounts.google.com/o/oauth2/auth?redirect_uri=http://localhost:8080/DSTAProject/googleAPI.htm&response_type=code&client_id=1070885696038-32m83k9ties5m7qsi4g6v8dfo28f2r9g.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar&approval_prompt=force&access_type=offline

将所有内容重定向到我获取授权令牌的servlet,并尝试使用访问令牌来解析此令牌。我知道我必须做另一个请求,这是我的代码:

String auth_code = request.getParameter("code");
     String codeClient = "?code="+ auth_code +"&client_id=1070885696038-32m83k9ties5m7qsi4g6v8dfo28f2r9g.apps.googleusercontent.com&";
     String secretUri = "client_secret=myclientsecret&" + "redirect_uri=http://localhost:8080/DSTAProject/&"
          + "grant_type=authorization_code";

     String postString = codeClient + secretUri;

     HttpURLConnection connection = null;  

     URL url = new URL("https://accounts.google.com/o/oauth2/token");

     connection = (HttpURLConnection)url.openConnection();
     connection.setRequestMethod("POST");
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
     connection.setUseCaches (false);
     connection.setDoInput(true);
     connection.setDoOutput(true);

      connection.setRequestProperty("Content-Length", "" + 
               Integer.toString(postString.getBytes().length));

      DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
      wr.writeBytes (postString);
      wr.flush ();
      wr.close ();

      //Get Response    
      InputStream is = connection.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      StringBuffer response1 = new StringBuffer(); 
      while((line = rd.readLine()) != null) {
        response1.append(line);
        response1.append('\r');
      }
      rd.close();
      System.out.println(response1.toString());


    connection.disconnect(); 

但是我收到了这个错误:

Server returned HTTP response code: 400 for URL: https://accounts.google.com/o/oauth2/token

有人可以帮助我吗?

0 个答案:

没有答案