使用Graph API将图像从.NET发布到Facebook墙 [英] Posting image from .NET to Facebook wall using the Graph API

查看:145
本文介绍了使用Graph API将图像从.NET发布到Facebook墙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Facebook的Javascript API来开发需要能够将图像发布到用户墙的应用程序。
这个应用程序的一部分需要是服务器端的,因为它需要将图像数据发布为multipart / form-data。


$ b $注意:这不是使用post的简单版本,而是真正的照片方法。



http://graph.facebook.com/me/photos



我想我'面对两个问题,一个.NET和一个Facebook问题:



Facebook问题:我不太确定所有参数是否应该发送作为多部分/表单数据(包括access_token和消息)。唯一的代码示例是使用cUrl util / application。



.NET问题:我从来没有发布多部分/表单数据请求.NET,我不知道.NET是否自动创建mime部分,或者我必须以某种特殊方式编码参数。



这有点很难调试,因为我从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;
如果(username!= null&& username!=&& &&密码!= null&&密码!=)
{
request.PreAuthenticate =真正;
request.Credentials = new NetworkCredential(username,password).GetCredential(new Uri(finishedUrl),Basic);
}
//写参数以请求身体
流requestBodyStream = request.GetRequestStream();
Encoding requestParameterEncoding = Encoding.GetEncoding(requestCharset);
byte [] parametersForBody = requestParameterEncoding.GetBytes(parameters);
requestBodyStream.Write(parametersForBody,0,parametersForBody.Length);
/ *
这不工作
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();
}
}


解决方案

是如何上传二进制数据的示例。但是上传到/ me / photos不会将图像发布到墙壁(图像保存到您的应用程序的专辑中,我被困在如何在feed中发布,另一种方法是将图像发布到Wall专辑,通过URL == graph.facebook.com/%wall-album-id%/photos ,但没有找到任何方法来创建这样的相册(用户在上传时创建它

  {
string boundary =----------- ----------------+ DateTime.Now.Ticks.ToString(x);
uploadRequest =(HttpWebRequest)WebRequest.Create(@https:// graph.facebook.com/me/photos);
uploadRequest.ServicePoint.Expect100Continue = false;
uploadRequest.Method =POST;
uploadRequest.UserAgent =Mozilla / 4.0 ; Windows NT);
uploadRequest.ContentType =multipart / form-data; boundary =+ boundary;
uploadRequest.KeepAlive = false;

StringBuilder sb = new StringBuilder ();

string formdataT emplate = - {0} \r\\\
Content-Disposition:form-data; name = \{1} \\r\\\
\r\\\
{2} \r\\\
;
sb.AppendFormat(formdataTemplate,boundary,access_token PercentEncode(FacebookAccessToken));
sb.AppendFormat(formdataTemplate,boundary,message,PercentEncode(This is a image));

string headerTemplate = - {0} \r\\\
Content-Disposition:form-data;名称= \ {1} \; filename = \{2} \\r\\\
Content-Type:{3} \r\\\
\r\\\
;
sb.AppendFormat(headerTemplate,boundary, source,file.png,@application / octet-stream);

string formString = sb.ToString();
byte [] formBytes = Encoding.UTF8.GetBytes (formString);
byte [] trailingBytes = Encoding.UTF8.GetBytes(\r\\\
--+ boundary +--\\\);

long imageLength = imageMemoryStream.Length;
long contentLength = formBytes.Length + imageLength + trailingBytes.Length;
uploadRequest.ContentLength = contentLength;

uploadRequest.AllowWriteStreamBuffering = false;
流strm_out = uploadRequest.GetRequestStream();

strm_out.Write(formBytes,0,formBytes.Length);

byte [] buffer = new Byte [检查((uint)Math.Min(4096,(int)imageLength))];
int bytesRead = 0;
int bytesTotal = 0;
imageMemoryStream.Seek(0,SeekOrigin.Begin );
while((bytesRead = imageMemoryStream.Read(buffer,0,buffer.Length))!= 0)
{
strm_out.Write(buffer,0,bytesRead); bytesTotal + = bytesRead;
gui.OnUploadProgress(this,(int)(bytesTotal * 100 / imageLength));
}

strm_out.Write(trailingBytes,0,trailingBytes.Length);

strm_out.Close();

HttpWebResponse wresp = uploadRequest.GetResponse()作为HttpWebResponse;
}


I'm using the Facebooks Javascript API to develop an application that will need to be able to post an image to a users wall. That part of the app needs to be server-side as far as I can tell, since it needs to post the image data as "multipart/form-data".

Note: It's not the simple version using "post", but the real "photos" method.

http://graph.facebook.com/me/photos

I think I'm facing two problems, a .NET and a Facebook problem:

Facebook problem: I'm not quite sure if all parameters should be send as multipart/form-data (including the access_token and message). The only code example there is uses the cUrl util/application.

.NET problem: I have never issued multipart/form-data requests from .NET , and I'm not sure if .NET automatically creates the mime-parts, or if I have to encode the parameters in some special way.

It's a bit hard to debug, since the only error response I get from the Graph API is "400 - bad request". Below is the code as it looked when I decided to write this question (yes, it's a bit verbose :-)

The ultimate answer would of course be a sample snippet posting an image from .NET, but I can settle for 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;
//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();
    }
}

解决方案

Here is a sample of how to upload binary data. But an uploading to /me/photos won't publish the image into wall :( The image saving into your app's album. I'm stuck on how to announce it in the feed. Yet another way is to post an image into "Wall Album", by URL=="graph.facebook.com/%wall-album-id%/photos". But didn't found any way to create sucha album (user creates it when uploading an image via the site).

{
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    uploadRequest = (HttpWebRequest)WebRequest.Create(@"https://graph.facebook.com/me/photos");
    uploadRequest.ServicePoint.Expect100Continue = false;
    uploadRequest.Method = "POST";
    uploadRequest.UserAgent = "Mozilla/4.0 (compatible; Windows NT)";
    uploadRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    uploadRequest.KeepAlive = false;

    StringBuilder sb = new StringBuilder();

    string formdataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n";
    sb.AppendFormat(formdataTemplate, boundary, "access_token", PercentEncode(facebookAccessToken));
    sb.AppendFormat(formdataTemplate, boundary, "message", PercentEncode("This is an image"));

    string headerTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n";
    sb.AppendFormat(headerTemplate, boundary, "source", "file.png", @"application/octet-stream");

    string formString = sb.ToString();
    byte[] formBytes = Encoding.UTF8.GetBytes(formString);
    byte[] trailingBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

    long imageLength = imageMemoryStream.Length;
    long contentLength = formBytes.Length + imageLength + trailingBytes.Length;
    uploadRequest.ContentLength = contentLength;

    uploadRequest.AllowWriteStreamBuffering = false;
    Stream strm_out = uploadRequest.GetRequestStream();

    strm_out.Write(formBytes, 0, formBytes.Length);

    byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)imageLength))];
    int bytesRead = 0;
    int bytesTotal = 0;
    imageMemoryStream.Seek(0, SeekOrigin.Begin);
    while ((bytesRead = imageMemoryStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        strm_out.Write(buffer, 0, bytesRead); bytesTotal += bytesRead;
        gui.OnUploadProgress(this, (int)(bytesTotal * 100 / imageLength));
    }

    strm_out.Write(trailingBytes, 0, trailingBytes.Length);

    strm_out.Close();

    HttpWebResponse wresp = uploadRequest.GetResponse() as HttpWebResponse;
}

这篇关于使用Graph API将图像从.NET发布到Facebook墙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆