发送“&”时格式错误的字符串异常在Json到AppEngine

时间:2013-03-02 17:47:42

标签: c# google-app-engine post encoding windows-phone-8

我正在尝试将Facebook图形链接发送到AppEngine服务器。我收到“格式错误的字符串异常”。这是我将json发送到服务器的方法:

public async Task<string> SendJSONData(string urlToCall, string JSONData)
    {
        // server to POST to
        string url = urlToCall;

        // HTTP web request
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/x-www-form-urlencoded";
        httpWebRequest.Method = "POST";

        // Write the request Asynchronously 
        using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
                                                                 httpWebRequest.EndGetRequestStream, null))
        {
            //create some json string
            string json = "action=" + JSONData;

            // convert json to byte array
            byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);

            // Write the bytes to the stream
            await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
        }

        WebResponse response = await httpWebRequest.GetResponseAsync();
        StreamReader requestReader = new StreamReader(response.GetResponseStream());
        String webResponse = requestReader.ReadToEnd();
        return webResponse; }

以下是我用Fiddler嗤之以鼻的事情:

POST http://x.appspot.com/register HTTP/1.1
Accept: */*
Content-Length: 376
Accept-Encoding: identity
Content-Type: application/x-www-form-urlencoded
User-Agent: NativeHost
Host: x.appspot.com
Connection: Keep-Alive
Pragma: no-cache

action={
  "mailFb": "mail@gmail.com",
  "userName": "Michael",
  "userSurname": "w00t",
  "nickname": "Michael w00t",
  "userSex": "male",
  "userAvatar": "https://graph.facebook.com/myperfectid/picture?type=large&access_token=BlahblahblahblahToken"
}

所以一切看起来都很好,但问题是我在AppEngine日志中收到以下错误:

2013-03-02 17:52:10.431 /register 500 56ms 0kb NativeHost
W 2013-03-02 17:52:10.427 /register com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 7 column 79 at com.google.g
C 2013-03-02 17:52:10.429 Uncaught exception from servlet com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 7 colu

我设法将问题缩小到其来源,即“&amp;”字符。所以我的问题是,如何修复代码,以便它可以与AppEngine一起使用。 哦,这是我如何阅读服务器上收到的数据:

gson.fromJson(reader, User.class);

1 个答案:

答案 0 :(得分:0)

您声称发送“Content-Type: application/x-www-form-urlencoded”的事实凸显了这个问题 但事实并非如此。因此错误。

&的正确编码为&amp;