使用 HttpClient 将照片上传到 Facebook

发布于 2024-10-08 19:10:38 字数 1675 浏览 0 评论 0原文

我正在尝试使用以下代码通过 Graph API 将照片上传到 Facebook。我不断收到“错误请求”,但不知道为什么。我可以使用具有相同参数的curl 很好地上传照片。我正在使用 Java 和 HttpClient。

    PostMethod filePost = new PostMethod('https://graph.facebook.com/me/photos');
    filePost.setParameter('access_token', 'my-access-token')
    filePost.setParameter('message', 'test image')

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    try {
      println("Uploading " + file.getName() + " to 'https://graph.facebook.com/me/photos'");
      Part[] parts = [new FilePart('source', file.getName(), file)]
      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      HttpClient client = new HttpClient();
      client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
      int status = client.executeMethod(filePost);
      if (status == HttpStatus.SC_OK) {
        println(
                "Upload complete, response=" + filePost.getResponseBodyAsString()
        );
      } else {
        println(
                "Upload failed, response=" + HttpStatus.getStatusText(status)
        );
      }
    } catch (Exception ex) {
      println("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      filePost.releaseConnection();
    }

更新:更多。我从响应中获取了更多信息,并得到以下信息:

{“error”:{“type”:“OAuthException”,“message”:“必须使用活动访问令牌来查询有关当前用户的信息。”}但这

似乎不对,因为我正在使用 facebook 在授权过程后返回给我的访问令牌。

工作卷曲代码:

curl -F 'access_token=my-access-token' -F 'source=@/path/to/image.jpg' -F 'message=Some caption' https://graph.facebook.com/me/photos

I am attempting to use the following code to upload a photo to Facebook using the Graph API. I keep getting "Bad Request" but not sure why. I can upload the photo just fine using curl with the same parameters. I'm using Java with HttpClient.

    PostMethod filePost = new PostMethod('https://graph.facebook.com/me/photos');
    filePost.setParameter('access_token', 'my-access-token')
    filePost.setParameter('message', 'test image')

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    try {
      println("Uploading " + file.getName() + " to 'https://graph.facebook.com/me/photos'");
      Part[] parts = [new FilePart('source', file.getName(), file)]
      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      HttpClient client = new HttpClient();
      client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
      int status = client.executeMethod(filePost);
      if (status == HttpStatus.SC_OK) {
        println(
                "Upload complete, response=" + filePost.getResponseBodyAsString()
        );
      } else {
        println(
                "Upload failed, response=" + HttpStatus.getStatusText(status)
        );
      }
    } catch (Exception ex) {
      println("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      filePost.releaseConnection();
    }

UPDATE: More to this. I grabbed some more info out the response and I am getting this:

{"error":{"type":"OAuthException","message":"An active access token must be used to query information about the current user."}}

But that doesn't seem right as I'm using the access token that facebook gives back to me after the authorize process.

Working curl code:

curl -F 'access_token=my-access-token' -F 'source=@/path/to/image.jpg' -F 'message=Some caption' https://graph.facebook.com/me/photos

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

皇甫轩 2024-10-15 19:10:38

我解决了这个问题。我不需要将参数添加到 PostMethod,而是需要将 access_token 和消息添加到 Part[] 数组。完整代码:

    PostMethod filePost = new PostMethod('https://graph.facebook.com/me/photos');
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    try {
      println("Uploading " + file.getName() + " to 'https://graph.facebook.com/me/photos'");
      Part[] parts = [new FilePart('source', file.getName(), file), new StringPart('access_token', "${facebookData.access_token}"), new StringPart('message', 'some message')]
      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      HttpClient client = new HttpClient();
      client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
      int status = client.executeMethod(filePost);
      if (status == HttpStatus.SC_OK) {
        println("Upload complete, response=" + filePost.getResponseBodyAsString());
      } else {
        println("Upload failed, response=" + HttpStatus.getStatusText(status));
        // Create response
        StringBuilder notificationsSendResponse = new StringBuilder();
        byte[] byteArrayNotifications = new byte[4096];
        for (int n; (n = filePost.getResponseBodyAsStream().read(byteArrayNotifications)) != -1;) {
          notificationsSendResponse.append(new String(byteArrayNotifications, 0, n));
        }
        String notificationInfo = notificationsSendResponse.toString();
      }
    } catch (Exception ex) {
      println("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      filePost.releaseConnection();
    }

I solved the problem. Instead of adding the params to the PostMethod, I needed to add the access_token and message to the Part[] array. Full code:

    PostMethod filePost = new PostMethod('https://graph.facebook.com/me/photos');
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    try {
      println("Uploading " + file.getName() + " to 'https://graph.facebook.com/me/photos'");
      Part[] parts = [new FilePart('source', file.getName(), file), new StringPart('access_token', "${facebookData.access_token}"), new StringPart('message', 'some message')]
      filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
      HttpClient client = new HttpClient();
      client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
      int status = client.executeMethod(filePost);
      if (status == HttpStatus.SC_OK) {
        println("Upload complete, response=" + filePost.getResponseBodyAsString());
      } else {
        println("Upload failed, response=" + HttpStatus.getStatusText(status));
        // Create response
        StringBuilder notificationsSendResponse = new StringBuilder();
        byte[] byteArrayNotifications = new byte[4096];
        for (int n; (n = filePost.getResponseBodyAsStream().read(byteArrayNotifications)) != -1;) {
          notificationsSendResponse.append(new String(byteArrayNotifications, 0, n));
        }
        String notificationInfo = notificationsSendResponse.toString();
      }
    } catch (Exception ex) {
      println("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      filePost.releaseConnection();
    }
韬韬不绝 2024-10-15 19:10:38

您可以使用socialauth java api通过Web应用程序上传图像。

http://code.google.com/p/socialauth/

You can use the socialauth java api for uploading image through web application.

http://code.google.com/p/socialauth/

娜些时光,永不杰束 2024-10-15 19:10:38

这是方法的android版本

  private void postOnFacebook() {
        try {
            HttpPost httpPost = new HttpPost("https://graph.facebook.com/me/photos");
            MultipartEntity entity = new MultipartEntity();
            String base64Image = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASSURBVBhXY3gro4KMKOPLqAAAq/UdZuRmLacAAAAASUVORK5CYII=";
            byte[] imageData = Base64.decode(base64Image, 0);
            entity.addPart("access_token", new StringBody("your access token"));
            entity.addPart("message", new StringBody("test msg"));
            entity.addPart("source", new ByteArrayBody(imageData, "test"));
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            httpPost.getParams().setBooleanParameter(USE_EXPECT_CONTINUE, false);
            httpPost.setEntity(entity);
            HttpResponse resp = httpclient.execute(httpPost);
            HttpEntity entity2 = resp.getEntity();
            if (entity != null) {
                String responseBody = EntityUtils.toString(entity2);
                responseBody.toString();
            }
        } catch (Exception ex) {

            ex.printStackTrace();
        }
    }

this is the android version of method

  private void postOnFacebook() {
        try {
            HttpPost httpPost = new HttpPost("https://graph.facebook.com/me/photos");
            MultipartEntity entity = new MultipartEntity();
            String base64Image = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASSURBVBhXY3gro4KMKOPLqAAAq/UdZuRmLacAAAAASUVORK5CYII=";
            byte[] imageData = Base64.decode(base64Image, 0);
            entity.addPart("access_token", new StringBody("your access token"));
            entity.addPart("message", new StringBody("test msg"));
            entity.addPart("source", new ByteArrayBody(imageData, "test"));
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            httpPost.getParams().setBooleanParameter(USE_EXPECT_CONTINUE, false);
            httpPost.setEntity(entity);
            HttpResponse resp = httpclient.execute(httpPost);
            HttpEntity entity2 = resp.getEntity();
            if (entity != null) {
                String responseBody = EntityUtils.toString(entity2);
                responseBody.toString();
            }
        } catch (Exception ex) {

            ex.printStackTrace();
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文