开发者

C# & Facebook API

开发者 https://www.devze.com 2023-02-06 05:27 出处:网络
I\'m currently using the Facebook API and C#. What i\'m trying to do is upload an image to an event. I\'ve tried two methods, but neither seem to work. Could someone please take a look.

I'm currently using the Facebook API and C#.

What i'm trying to do is upload an image to an event.

I've tried two methods, but neither seem to work. Could someone please take a look.

Method 1

        Dictionary<string, string> args = new Dictionary<string, string>();
        string source = "@test.jpg";
        string relpath = "/1234456789/photos";
        args.Add("message", "sssssss");
        args.Add("access_token", api.AccessToken);
        args.Add("source", source);
        api.Post(relpath, args);

Method 2

        HttpWebRequest request = (HttpWebRequest)WebRequest.开发者_JS百科Create(String.Format("http://graph.facebook.com/1234456789/photos")); 
        request.ContentType = "multipart/form-data"; 
        request.Method = "POST";

        string path = HttpUtility.UrlEncode("test.jpg");
        request.BeginGetRequestStream(ar => 
        { 
            using (StreamWriter writer = new StreamWriter((ar.AsyncState as HttpWebRequest).EndGetRequestStream(ar))) 
            { 
                writer.Write("{0}={1}&", "message", HttpUtility.UrlEncode("Test")); 
                writer.Write("{0}=@{1}&", "source", path);
                writer.Write("{0}={1}", "access_token",
                    api.AccessToken); 
            } 
        }, request);

Method 3

        WebClient client = new WebClient();

        byte[] responseBinary = client.UploadFile("http://localhost:61689/Widgets/test2.aspx", "POST", @"C:\test.jpg");

        string response = Encoding.UTF8.GetString(responseBinary);

        Dictionary<string, string> args = new Dictionary<string, string>();

        string relpath = "https://graph.facebook.com/me/picture";
        args.Add("message", "sssssss");
        args.Add("access_token", GetAccessToken(code));
        args.Add("source", response); 

        api.Post(relpath, args);

In method 3 i'm trying to create the response and write that. I'm getting 400 bad request.

The image 'test.jpg' currently sits in my website root, same as the page calling it.


Hey Robert, not sure if this is what is causing it, but in Example 1 it looks like you are trying to use a string literal on the JPG name, but if so, the @ symbol needs to be outside the quotes...

@"good morning" // a string literal


It looks like you are only passing the filename of the photo to upload. Are you using a library that will read the actual photo contents from disk? If not, you'll need to do that yourself and write the contents to the request.

The format for writing the photo contents to the request will depend on the expectations of the API you are writing to (multi-part, etc.).

0

精彩评论

暂无评论...
验证码 换一张
取 消