2012-04-04 109 views
-1

浏览URL,并给予同意:谷歌API第3版:将活动添加到谷歌日历

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/[email protected]/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?

+2

什么语言是这个代码?看看这个博客文章:http://bittwiddlers.org/?p=212#awp::?p=212 – HK1 2012-04-08 03:05:56

回答

-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); 
+0

嗨,你可以请分享完整的工作代码。 @Ravi – 2017-02-28 13:00:34