使用发布请求在Google日历中创建新活动

时间:2012-07-25 12:22:42

标签: java post google-calendar-api

我正在尝试使用POST请求在Google日历中创建一个新事件,但我总是遇到400错误。

到目前为止,我有这个:

String url = "https://www.googleapis.com/calendar/v3/calendars/"+ calendarID + "/events?access_token=" + token;
String data = "{\n-\"end\":{\n\"dateTime\": \"" + day + "T" + end +":00.000Z\"\n},\n" +
                        "-\"start\": {\n \"dateTime\": \"" + day + "T" + begin + ":00.000Z\"\n},\n" +
                        "\"description\": \"" + description + "\",\n" +
                        "\"location\": \"" + location + "\",\n" +
                        "\"summary\": \"" + title +"\"\n}";



System.out.println(data);

URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
String a = connection.getRequestMethod();
connection.setRequestProperty("Content-Type", "application/json"); 
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Authorization", "OAuth" + token); 
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(data);
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
while ((line = rd.readLine()) != null) {
   System.out.println(line);
}
wr.close();
rd.close();

但是当我创建BufferedReader以读取我的响应时,我得到400错误。怎么了?

提前致谢!

1 个答案:

答案 0 :(得分:3)

您是否尝试过使用Google APIs Client Library for Java?它将使这样的操作更加简单。一旦配置了客户端库并创建了服务对象,就可以相对轻松地进行API调用。此示例创建事件并将其插入日历:

Event event = new Event();

event.setSummary("Appointment");
event.setLocation("Somewhere");

ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
attendees.add(new EventAttendee().setEmail("attendeeEmail"));
// ...
event.setAttendees(attendees);

Date startDate = new Date();
Date endDate = new Date(startDate.getTime() + 3600000);
DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
event.setStart(new EventDateTime().setDateTime(start));
DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
event.setEnd(new EventDateTime().setDateTime(end));

Event createdEvent = service.events().insert("primary", event).execute();

System.out.println(createdEvent.getId());

它假设您已按照here概述创建了服务对象。