我正在使用Google Calendar API。出于好奇,我没有使用Google库,所以我可以自己编写。
我无法制作新日历。
身份验证有效,因为此获取请求有效:https://developers.google.com/google-apps/calendar/v3/reference/calendarList/list
为了制作新的日历,我使用了:https://developers.google.com/google-apps/calendar/v3/reference/calendarList/insert
我写:
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,false);
HttpPost httppost = new HttpPost("https://www.googleapis.com/calendar/v3/users/me/calendarList");
httppost.addHeader("Authorization", "Bearer " + token); //authentication
httppost.addHeader("Host", "googleapis.com");
StringEntity params = new StringEntity("{\"id\": \"TestSchedule\",\"defaultReminders\":[{\"method\": \"popup\",\"minutes\":10}]}");
httppost.setEntity(params);
//EXECUTE REQUEST
HttpResponse postResponse = httpclient.execute(httppost);
//RESPONSE
HttpEntity entity = postResponse.getEntity();
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
httppost.releaseConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
此外,获得正确令牌的范围是:https://www.googleapis.com/auth/calendar
这应该是正确的。我认为问题出在我的发帖请求正文中?
因此,获取请求有效,因此我假设我的身份验证过程正确并且获得了正确的令牌。执行此发布请求而不是获取请求结果是302响应代码。我得到的新URL是google的主页,根据参考页,我应该获得日历资源。
最佳答案
The following code working. please u can check it now.
{
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS,false);
HttpGet httpget = new HttpGet("https://www.googleapis.com/calendar/v3/users/me/calendarList");
httpget.addHeader("Authorization", "Bearer " + accessToken);
//HttpPost httppost = new HttpPost("https://www.googleapis.com/calendar/v3/users/me/calendarList");
//httppost.addHeader("Authorization", "Bearer " + accessToken); //authentication
// httppost.addHeader("Host", "googleapis.com");
/* StringEntity params = new StringEntity("{\"id\":}");
httppost.setEntity(params);*/
//EXECUTE REQUEST
HttpResponse postResponse = httpclient.execute(httpget);
//RESPONSE
HttpEntity entity = postResponse.getEntity();
String responseBody1 = EntityUtils.toString(entity);
logger.debug(responseBody1);
}