Pregunta

Estoy intentando utilizar el código siguiente para subir una foto a Facebook utilizando la API de gráficos. Me pone "Bad Request" pero no sabe por qué. Puedo subir la foto apenas muy bien el uso de rizo con los mismos parámetros. Estoy usando Java con 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();
    }

ACTUALIZACIÓN: Más de esto. Agarré algo más de información a cabo la respuesta y yo estoy haciendo esto:

{ "error": { "type": "OAuthException", "mensaje": "Un testigo de acceso activo debe ser utilizada para consulta de información sobre el usuario actual"}}

Pero eso no me parece bien que estoy usando el token de acceso que Facebook da de nuevo a mí después del proceso de autorizar.

Trabajo rizo código:

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

Solución

Me solucionó el problema. En lugar de agregar los parametros a la PostMethod, tenía que añadir el señal_acceso y el mensaje a la matriz de la Parte []. código completo:

    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();
    }

Otros consejos

Puede utilizar la API de Java socialauth de subir una imagen a través de la aplicación web.

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

esta es la versión androide de método

  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();
        }
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top