1

我正在尝试按照文档通过 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 有效且未过期,应用程序密钥正确。

我做错了什么或错过了什么?

提前致谢,

4

2 回答 2

2

我不确定这是否能解决您的问题,但有几点需要注意。在这种情况下,不要使用 Environment.NewLine,如果您的代码在 Windows、Mac 或 Linux 上运行,您的网络流量不应改变。Http 1.1需要 CRLF

您将帖子的正文编码为 UTF-8 是的,您没有告诉服务器您正在使用哪种编码。您所有的字符都是低位 ASCII,所以这无关紧要,但为了完整起见,您的内容类型应该是

 httpWebRequest.ContentType = "application/json ; charset=UTF-8";

除此之外,我看不到您的代码有问题,附加一个透明的回显代理(Charles 或 fiddler)可能会很好,这样您就可以通过网络看到您的请求是什么样的。从他们发送的日历示例中

要求

POST https://www.googleapis.com/calendar/v3/calendars?key={YOUR_API_KEY}

Content-Type:  application/json
Authorization:  Bearer ya29.AHES6ZR3F6ByTg1eKVkjegKyWIukodK8KGSzY-ea1miGKpc
X-JavaScript-User-Agent:  Google APIs Explorer

{
 "summary": "Test Calendar"
}

回复

200 OK

- Show headers -

{

 "kind": "calendar#calendar",
 "etag": "\"NybCyMgjkLQM6Il-p8A5652MtaE/ldoGyKD2MdBs__AsDbQ2rHLfMpk\"",
 "id": "google.com_gqua79l34qk8v30bot94celnq8@group.calendar.google.com",
 "summary": "Test Calendar"
}

希望有所帮助,意识到它可能不会。

于 2012-12-10T12:55:26.630 回答
1

我想通了,让它工作了!

虽然 David 的建议本身并不能解决问题,但他告诉我使用数据包嗅探器(我最终使用了 Wireshark,但这并不是重点),从而使我走上了正确的道路。

事实证明,我的简化代码中有两个错误。一个如此明显,让我脸红,一个更狡猾。

首先,

using (var streamWriter = new StreamWriter(stream))
{
    streamWriter.Write(Encoding.UTF8.GetBytes(requestText));
}

当然应该是

using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
{
    streamWriter.Write(requestText);
}

由于 streamWriter.Write 对参数执行 ToString(),而 Byte[].ToString() 只返回“System.Byte[]”。尴尬!

其次,默认的 UTF8 编码添加了字节顺序标记\357\273\277,这也导致内容在google 上无效。我在stackoverflow上找到了如何解决这个问题

因此,对于任何为此苦苦挣扎的人,这是最终的解决方案。

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";
// added the character set to the content-type as per David's suggestion
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.CookieContainer = new CookieContainer();

// replaced Environment.Newline by CRLF as per David's suggestion
var requestText = string.Join
(
    "\r\n",
    "{",
    " \"summary\": \"Test Calendar 123\"",
    "}"
);

using (var stream = httpWebRequest.GetRequestStream())
// replaced Encoding.UTF8 by new UTF8Encoding(false) to avoid the byte order mark
using (var streamWriter = new StreamWriter(stream, new UTF8Encoding(false)))
{
    streamWriter.Write(requestText);
}

希望这对某人有帮助!

于 2013-01-07T12:38:50.153 回答