我正在使用Facebook的JavaScript API开发一个应用程序,需要能够将图片发布到用户的墙上。据我所知,这部分应用程序需要在服务器端完成,因为它需要将图像数据发布为“multipart/form-data”格式。
注意:这不是使用“post”简单版本,而是真正的“photos”方法。
这有点难以调试,因为Graph API仅返回“400 - 错误请求”的错误响应。 以下是我撰写本文时的代码(是的,它有点冗长:-)
当然,最终答案将是从.NET发布图像的示例片段,但我可以接受更少的内容。
注意:这不是使用“post”简单版本,而是真正的“photos”方法。
http://graph.facebook.com/me/photos
我认为我面临两个问题,一个是.NET问题,另一个是Facebook问题: Facebook问题:我不确定是否应该将所有参数作为multipart/form-data发送(包括access_token和message)。唯一的代码示例使用了cUrl工具/应用程序。 .NET问题:我从未从.NET发出过multipart/form-data请求,我不确定.NET是否会自动创建mime-parts,或者我是否需要以某种特殊的方式对参数进行编码。这有点难以调试,因为Graph API仅返回“400 - 错误请求”的错误响应。 以下是我撰写本文时的代码(是的,它有点冗长:-)
当然,最终答案将是从.NET发布图像的示例片段,但我可以接受更少的内容。
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;
//application/x-www-form-urlencoded | multipart/form-data
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");
}
//write parameters to request body
Stream requestBodyStream = request.GetRequestStream();
Encoding requestParameterEncoding = Encoding.GetEncoding(requestCharset);
byte[] parametersForBody = requestParameterEncoding.GetBytes(parameters);
requestBodyStream.Write(parametersForBody, 0, parametersForBody.Length);
/*
This wont work
byte[] startParm = requestParameterEncoding.GetBytes("&source=");
requestBodyStream.Write(startParm, 0, startParm.Length);
byte[] fileBytes = File.ReadAllBytes(Server.MapPath("images/sample.jpg"));
requestBodyStream.Write( fileBytes, 0, fileBytes.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();
}
}