Friday, September 20, 2013

Publish Facebook Posts Using C#

In this post I want to show, how to publish posts on the own Facebook page or the page of someone else (of course, only if this is allowed).

Therefor we create a new app in the developer app section. Then we provide ourself with an access token and set the right publish_action, after which we have to log on.
(Note: I recommend reading this new post regarding access tokens, since Facebook decreased their validity a lot.)
The app then quasi remembers our account, when executing it uses it and is able to do everything according to the obtained rights. The right publish_action describes, that the app may publish posts etc.
For publishing we have to use the HTTP POST method. The address, to which to send the data, is https://graph.facebook.com/useridentifier/feed/.
useridentifier thereby has to be replaced by the identifier of the target user, as for example ID or unique name. me is an abbreviation for the own account.
If we want to publish a post, we have to send the access token after the parameter access_token as well as the content of the post after the parameter message and then start a POST request.

The following sample code writes the text "Hallo Welt" on the own page:


            string URL;
            URL = "https://graph.facebook.com/me/feed/";

            WebRequest MyRequest;
            MyRequest = WebRequest.Create(URL);
            MyRequest.Method = "POST";

            Stream DataStream = MyRequest.GetRequestStream();
            Byte[] Data = Encoding.UTF8.GetBytes("access_token=xyz123&message=Hallo Welt");
            DataStream.Write(Data, 0, Data.Length);
            DataStream.Close();

            MyRequest.GetResponse();

No comments:

Post a Comment