I am using the Facebooks Javascript API to develop an application that should be able to post an image to a user's wall. This part of the application should be server-side, as far as I can tell, since it should place image data as "multipart / form-data".
Note. This is not a simple version using "post", but the real "photos" method.
http://graph.facebook.com/me/photos
I think I have two problems: .NET and Facebook problem:
Problem with Facebook: I'm not quite sure that all parameters should be sent as multipart / form-data (including access_token and message). The only code sample uses the cUrl util / application utility.
.NET Problem: I have never produced multidisciplinary / form data requests from .NET, and I'm not sure if .NET automatically creates mime parts, or if I need to encode parameters in some special way.
It's a little tricky to debug, as the only error response I get from the Graph API is "400 is a bad request." Below is the code that looked when I decided to write this question (yes, this is a bit detailed :-)
The final answer, of course, would be a sample fragment sending an image from .NET, but I can count on less.
string username = null;
string password = null;
int timeout = 5000;
string requestCharset = "UTF-8";
string responseCharset = "UTF-8";
string parameters = "";
string responseContent = "";
string finishedUrl = "https://graph.facebook.com/me/photos";
parameters = "access_token=" + facebookAccessToken + "&message=This+is+an+image";
HttpWebRequest request = null;
request = (HttpWebRequest)WebRequest.Create(finishedUrl);
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = "multipart/form-data";
request.Timeout = timeout;
request.AllowAutoRedirect = false;
if (username != null && username != "" && password != null && password != "")
{
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(username, password).GetCredential(new Uri(finishedUrl), "Basic");
}
Stream requestBodyStream = request.GetRequestStream();
Encoding requestParameterEncoding = Encoding.GetEncoding(requestCharset);
byte[] parametersForBody = requestParameterEncoding.GetBytes(parameters);
requestBodyStream.Write(parametersForBody, 0, parametersForBody.Length);
requestBodyStream.Close();
HttpWebResponse response = null;
Stream receiveStream = null;
StreamReader readStream = null;
Encoding responseEncoding = System.Text.Encoding.GetEncoding(responseCharset);
try
{
response = (HttpWebResponse) request.GetResponse();
receiveStream = response.GetResponseStream();
readStream = new StreamReader( receiveStream, responseEncoding );
responseContent = readStream.ReadToEnd();
}
finally
{
if (receiveStream != null)
{
receiveStream.Close();
}
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
}
source
share