2012-07-25 41 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

相关问题