Google API v3:向Google日历添加活动

时间:2012-04-04 11:57:59

标签: java google-calendar-api

导航到网址并表示同意:

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/calendar&state=%2Fprofile&redirect_uri=http://localhost:8080/webapp_name/calendar/calendar.html?operation=oauth2callback&response_type=code&client_id=84294424369.apps.googleusercontent.com&approval_prompt=force 

我在我的方法中得到'代码',用于获取访问令牌,如

HttpClient client = new HttpClient();
String accessTokenURL = "https://accounts.google.com/o/oauth2/token";
PostMethod method = new PostMethod(accessTokenURL);     
method.addParameter("code",request.getParameter("code"));           method.addParameter("client_id","84294424369.apps.googleusercontent.com");
method.addParameter("client_secret","sPXaCrOX_19df5iXjII7ZlCp");            method.addParameter("redirect_uri",request.getRequestURL()+"?operation=oauth2callback");
method.addParameter("grant_type","authorization_code");

int returnCode = client.executeMethod(method);

HashMap gctoken =   (HashMap)new JSONDeserializer().deserialize(method.getResponseBodyAsString());

String accessToken = gctoken.get("access_token").toString();

现在使用上面的令牌将事件插入我的日历:

String accessTokenURL = "https://www.googleapis.com/calendar/v3/calendars/jude.law@gmail.com/events";

PostMethod method = new PostMethod(accessTokenURL);
method.addParameter("access_token",accessToken);
method.addParameter("summary","New york trip");
method.addParameter("description","Chicago desc");
method.addParameter("start",(new Date()).toString());
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(Calendar.HOUR,1);           
method.addParameter("end",cal.getTime().toString());

int returnCode = client.executeMethod(method);

System.out.println("Event created------->   "+method.getResponseBodyAsString());

上面的插入代码给出了错误

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

HOW to solve this Credentials problem and create entry in my google calendar?

1 个答案:

答案 0 :(得分:-1)

好的,它已经解决了。

我做了

HttpClient client = new HttpClient();   
String accessTokenURL1 = "https://www.googleapis.com/calendar/v3/calendars/"+calId+"/events";
PostMethod method = new PostMethod(accessTokenURL1);
method.setRequestHeader("Content-Type","application/json");         
method.setRequestHeader("Authorization","OAuth "+token);
method.setRequestBody(json);
int returnCode = client.executeMethod(method);