【问题标题】:VB.NET Upload Photos to Facebook using Graph APIVB.NET 使用 Graph API 将照片上传到 Facebook
【发布时间】:2023-03-17 23:30:01
【问题描述】:

寻找一些代码来使用 VB.NET 中的 Graph API 将照片上传到 facebook。我有 Facebook C# SDK,但据我所知它不支持上传照片。

访问照片工作正常,我也可以将其他内容发送到 Facebook。只是没有照片。

facebook 文档谈到将文件作为表单多部分请求附加,但我不知道该怎么做。要说它没有很好的记录是轻描淡写。即使是我雇来做这种事情的人也无法让它发挥作用。

我找到了这个:Upload Photo To Album with Facebook's Graph API,但它只描述了如何在 PHP 中做到这一点。

我还看到来自不同站点的不同方法将照片的 URL 作为 HTTP 请求的一部分传递,但在多次尝试本地或远程 URL 后,我一直收到错误的 url 错误或类似的东西。

有什么想法吗?

【问题讨论】:

    标签: vb.net facebook facebook-graph-api


    【解决方案1】:

    您需要将 POST 请求中的 Image 传递给 Graph API(需要 publish_stream 权限)。 Facebook 文档中提到的内容是正确的。以下是可以完成工作的示例代码。在方法中使用它。 (代码在 C# 中)

    传奇 <content> : 你需要提供信息。

    更新 请发布 cmets 以改进代码。

    string ImageData;
    string queryString = string.Concat("access_token=", /*<Place your access token here>*/);
    string boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
    
    StringBuilder sb = String.Empty;
    sb.Append("----------").Append(boundary).Append("\r\n");
    sb.Append("Content-Disposition: form-data; filename=\"").Append(/*<Enter you image's flename>*/).Append("\"").Append("\r\n");
    sb.Append("Content-Type: ").Append(String.Format("Image/{0}"/*<Enter your file type like jpg, bmp, gif, etc>*/)).Append("\r\n").Append("\r\n");
    
    using (FileInfo file = new FileInfo("/*<Enter the full physical path of the Image file>*/"))
    {
        ImageData = file.OpenText().ReadToEnd();
    }
    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString());
    byte[] fileData = Encoding.UTF8.GetBytes(ImageData);
    byte[] boundaryBytes = Encoding.UTF8.GetBytes(String.Concat("\r\n", "----------", boundary, "----------", "\r\n"));
    var postdata = new byte[postHeaderBytes.Length + fileData.Length + boundaryBytes.Length];
    Buffer.BlockCopy(postHeaderBytes, 0, postData, 0, postHeaderBytes.Length);
    Buffer.BlockCopy(fileData, 0, postData, postHeaderBytes.Length, fileData.Length);
    Buffer.BlockCopy(boundaryBytes, 0, postData, postHeaderBytes.Length + fileData.Length, boundaryBytes.Length);
    
    var requestUri = new UriBuilder("https://graph.facebook.com/me/photos");
    requestUri.Query = queryString;
    var request = (HttpWebRequest)HttpWebRequest.Create(requestUri.Uri);
    request.Method = "POST";
    request.ContentType = String.Concat("multipart/form-data; boundary=", boundary);
    request.ContentLength = postData.Length;
    
    using (var dataStream = request.GetRequestStream())
    {
          dataStream.Write(postData, 0, postData.Length);
    }
    
    request.GetResponse();
    

    【讨论】:

    • 我终于开始尝试这个,但我得到了相同的“远程服务器返回错误:(400) 错误请求。”我已经用其他方法得到了。我注意到你两次声明了请求变量,vb.net 不喜欢这样。
    • 哦,是的,对不起,我刚刚编辑了它.. 对于您的问题...您确定您使用的是有效的访问令牌(具有发布流扩展权限).. 因为该错误通常在您返回时返回没有有效的访问令牌。尝试在浏览器 (GET) 请求中使用带有访问令牌的 uri,你仍然会收到错误...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多