java - 使用发布请求在 Google 日历中创建新事件

标签 java post google-calendar-api

我正在尝试使用 POST 请求在 Google 日历中创建新 Activity ,但我总是收到 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 错误。怎么了?

提前致谢!

最佳答案

您是否尝试过使用 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所述.

关于java - 使用发布请求在 Google 日历中创建新事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11649616/

相关文章:

java - 将 JPanel 转换为二进制数组

google-calendar-api - 有关生成 iCal Feed 的问题

c# - Google API V 3.0 .Net 库和 Google OAuth2 如何处理刷新 token

java - Ant Ivy 不会设置编译类路径

java - URIBuilder build() 削减端口?

php - 检测 PHP 解析多维 POST 数据期间的错误

java - 尝试在 java 中上传图像时出现 NoSuchFileException

javascript - jQuery 跨域 POST 恶作剧

javascript - Google Calendar.Insert API 返回 400 'required'

java - 如何在单个值中表示 4 种 boolean 可能性