C#实现了facebook的新“批量”功能

时间:2011-03-18 20:08:44

标签: c# facebook httpwebrequest facebook-graph-api http-post

所以我正在尝试将新的“批量”功能用于图形API,其描述为here。我认为问题在于我使用POST提交数据的方式,而且我在调试时遇到了困难。它可能是一个JSON问题,但我不这么认为。 这是c#

        HttpWebRequest httpRequest =(HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
        httpRequest.Method = "POST";
        httpRequest.ContentType = "application/x-www-form-urlencoded";

        byte[] bytedata = Encoding.UTF8.GetBytes(o.ToString());
        httpRequest.ContentLength = bytedata.Length;

        Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytedata, 0, bytedata.Length);
        requestStream.Close();

        HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
        Stream responseStream = httpWebResponse.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);

        string APIData = reader.ReadToEnd();
        JObject MyApiData = JObject.Parse(APIData);

变量“o”包含以下JSON:

{
  "access_token": "[my real token]",
  "batch": [
    {
      "method": "get",
      "relative_url": "me"
    },
    {
      "method": "get",
      "relative_url": "me/friends"
    }
  ]
}

任何想法我做错了什么?它实际上输出了facebook的开发者网站文档....所以我认为这是一个线索,它搞砸了! - )

1 个答案:

答案 0 :(得分:3)

试试这个:                private void PostBatch(string _token)         {

        string p1 = "access_token=" + Server.UrlEncode(_token);
        string p2  = "&batch=" + Server.UrlEncode(" [ { \"method\": \"get\", \"relative_url\": \"me\" }, { \"method\": \"get\", \"relative_url\": \"me/friends\" } ]");

        try
        {

            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/");
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/x-www-form-urlencoded";

            byte[] bytedata = Encoding.UTF8.GetBytes(p1 + p2);
            httpRequest.ContentLength = bytedata.Length;

            Stream requestStream = httpRequest.GetRequestStream();
            requestStream.Write(bytedata, 0, bytedata.Length);
            requestStream.Close();

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
            Stream responseStream = httpWebResponse.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);

            string APIData = reader.ReadToEnd();
            Response.Write(APIData);
        }
        catch (Exception ex)
        { Response.Write(ex.Message.ToString() + "<br>"); }
       // JObject MyApiData = JObject.Parse(APIData);


    }