我試圖從測試控制檯應用程序中向Google日曆添加事件。 我通過我在Google API控制檯註冊的Web應用程序獲得了「https://www.googleapis.com/auth/calendar」作用域的token_refresh。 我在我的測試控制檯應用程序中使用此存儲的token_refresh來獲取access_token。 然後,我想將事件添加到與我擁有的refresh_token對應的用戶的日曆中。撰寫POST Http請求以添加Google Calendar API v3事件
所以我建立一個POST的HttpWebRequest如下:
HttpWebRequest request = WebRequest.Create("https://www.googleapis.com/calendar/v3/calendars/" + calendarID + "/events") as HttpWebRequest; // Where calendarID is like [email protected]
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構建不當和未知錯誤的佔位符。
請告訴我怎樣才能生成access_token @alexnaicu – Saravanakumar 2018-01-08 17:02:44