我正在尝试从测试控制台应用程序中将事件添加到 Google 日历。我通过在 Google API 控制台注册的 Web 应用程序为范围“https://www.googleapis.com/auth/calendar”获得了 token_refresh。我在我的测试控制台应用程序中使用这个存储的 token_refresh 来获取 access_token。然后我想在用户的日历中添加一个与我拥有的 refresh_token 相对应的事件。
所以我构建了一个 POST HttpWebRequest 如下:
HttpWebRequest request = WebRequest.Create("https://www.googleapis.com/calendar/v3/calendars/" + calendarID + "/events") as HttpWebRequest; // Where calendarID is like joe@gmail.com
request.Headers.Add("Authorization", "Bearer " + access_token);
request.Headers.Add("Accept-Charset", "UTF-8");
request.Headers.Add("ContentType", "application/json");
request.ProtocolVersion = HttpVersion.Version11;
request.KeepAlive = false;
request.Method = "POST";
GoogleCalendarEvent anEvent = new GoogleCalendarEvent();
anEvent.start = new GoogleCalendarEventTime(DateTime.Today);
anEvent.end = new GoogleCalendarEventTime(DateTime.Today);
string data = jsonSerializer.Serialize(anEvent); // jsonSerializer is a JavaScriptSerializer object
byte[] postData = Encoding.UTF8.GetBytes(data);
Stream ws = request.GetRequestStream();
ws.Write(postData, 0, postData.Length);
ws.Close();
WebResponse response = request.GetResponse(); // throws WebException The remote server returned an error: (400) Bad Request.
stream = new StreamReader(response.GetResponseStream());
string result = stream.ReadToEnd().Trim();
辅助类是:
private class GoogleCalendar
{
private string kind;
private string etag;
private string id;
private string summary;
private string timezone;
private string accesrole;
public string Kind
{
get { return this.kind;}
set { this.kind = value; }
}
public string Etag
{
get { return this.etag; }
set { this.etag = value; }
}
public string ID
{
get { return this.id; }
set { this.id = value; }
}
public string Summary
{
get { return this.summary; }
set { this.summary = value; }
}
public string TimeZone
{
get { return this.timezone; }
set { this.timezone = value; }
}
public string AccessRole
{
get { return this.accesrole; }
set { this.accesrole = value; }
}
}
private class GoogleCalendarEventTime
{
private DateTime _date;
public string date
{
get
{
return this._date.ToString("yyyy-mm-dd");
}
}
public GoogleCalendarEventTime(DateTime time)
{
this._date = time;
}
}
我的问题是,当我尝试获取请求的响应时,我收到了错误 400 错误请求。这种类型的错误代码既适用于 POST 构造错误的情况,也适用于未知错误的占位符。