【发布时间】:2012-11-16 02:37:00
【问题描述】:
我正在尝试按照documentation 通过 Google API 创建日历。我试图避免使用客户端库并通过自定义 webrequests 与 API 进行所有通信,到目前为止,这一直运行良好,但在这个特定的库中,我正在努力解决 “解析错误”。
请不要参考使用客户端库的解决方案(service.calendars().insert(...))。
这是我的代码的简化版本(仍然无法正常工作):
var url = string.Format
(
"https://www.googleapis.com/calendar/v3/calendars?key={0}",
application.Key
);
var httpWebRequest = HttpWebRequest.Create(url) as HttpWebRequest;
httpWebRequest.Headers["Authorization"] =
string.Format("Bearer {0}", user.AccessToken.Token);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.CookieContainer = new CookieContainer();
// Obviously the real code will serialize an object in our system.
// I'm using a dummy request for now,
// just to make sure that the problem is not the serialization.
var requestText =
"{" + Environment.NewLine
+ "\"summary\": \"test123\"" + Environment.NewLine
+ "}" + Environment.NewLine
;
using (var stream = httpWebRequest.GetRequestStream())
using (var streamWriter = new System.IO.StreamWriter(stream))
{
streamWriter.Write(System.Text.Encoding.UTF8.GetBytes(requestText));
}
// GetSafeResponse() is just an extension that catches the WebException (if any)
// and returns the WebException.Response instead of crashing the program.
var httpWebResponse = httpWebRequest.GetSafeResponse();
如您所见,我现在已经放弃发送序列化对象,我只是想用一个非常简单的虚拟请求让它工作:
{
"summary": "test123"
}
但响应仍然只是:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
accessToken有效且未过期,应用密钥正确。
我做错了什么或错过了什么?
提前致谢,
【问题讨论】:
-
您好,只是出于兴趣,您为什么反对使用客户端库?
-
因为它只是为已经相当复杂的项目增加了另一层复杂性,因为我们必须包含不受我们控制的代码,并且当它出现错误时我们可能无法修复自己/ 或中断,因为根据定义,REST 服务应该简单明了。我们的代码也使用相同的严肃方法与 FB 和 Twitter 同步,这一点都不难,除非像这种情况下,文档是错误的。
-
感谢您的回复:)
标签: c# google-api google-calendar-api