2012-07-25 116 views
1

我正嘗試使用POST請求在Google日曆中創建新事件,但我總是收到400錯誤。使用POST請求在Google日曆中創建新事件

到目前爲止,我有這樣的:

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錯誤。怎麼了?

在此先感謝!

回答

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服務對象。

+0

感謝您的回覆。我無法使用Google APis,因爲我使用的是GWT,並且它說與它不兼容。我發現我的錯誤是。我在數據字符串中有2個「 - 」信號,它不應該在那裏。 – 2012-07-30 14:11:38

+0

GWT還有一個庫:http://code.google.com/p/gwt-google-apis/ – 2012-07-30 16:54:25