Android/Java -- 将简单的文本发布到 Facebook 墙上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2953146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:53:26  来源:igfitidea点击:

Android/Java -- Post simple text to Facebook wall?

javaandroidfacebook

提问by RyanM

I'm trying to integrate posting to one's wall from within my app. I already have an area where the user can save his/her username and password (encrypted). I would like my program to recall the saved username and password, pass that to Facebook for authentication, and then allow the app to post simple text (maybe a link too) to the user's wall.

我正在尝试从我的应用程序中将帖子集成到一个人的墙上。我已经有一个用户可以保存他/她的用户名和密码(加密)的区域。我希望我的程序调用保存的用户名和密码,将其传递给 Facebook 进行身份验证,然后允许应用程序将简单的文本(也可能是链接)发布到用户的墙上。

That said, I've read everything on the developer pages at Facebook (the api looks completely foreign to me... I've never done any type of web app development before... just desktop apps), and experimented with the Java libraries herebut to be honest, I don't understand any of the various implementations. Some claim to be simple to use, but apparently they are all way above my head.

也就是说,我已经阅读了 Facebook 开发人员页面上的所有内容(api 对我来说看起来完全陌生……我以前从未做过任何类型的网络应用程序开发……只是桌面应用程序),并尝试了 Java这里的但老实说,我不了解任何各种实现。有些人声称使用起来很简单,但显然它们都在我的头上。

I've even tried messing with the official Facebook Android SDK, but that uses a webview interface, and I can't pass in the username and password for easy authentication. Plus, I'm still clueless as to how to post to the wall even after correct authentication.

我什至尝试过弄乱官方的 Facebook Android SDK,但它使用的是 webview 界面,而且我无法传递用户名和密码以进行轻松验证。另外,即使经过正确的身份验证,我仍然对如何张贴到墙上一无所知。

Please help. Thanks.

请帮忙。谢谢。

Oh, btw I already have a Facebook API key and Application ID.

哦,顺便说一句,我已经有了 Facebook API 密钥和应用程序 ID。

[UPDATE 1]

[更新 1]

For further clarification: If I use the following code snippet with the official Facebook Android SDK http://github.com/facebook/facebook-android-sdkwhat should I do next (after the user has logged-in)? This is unclear to me.

进一步说明:如果我将以下代码片段与官方 Facebook Android SDK http://github.com/facebook/facebook-android-sdk 一起使用,我接下来应该做什么(用户登录后)?这对我来说不清楚。

Facebook facebookClient = new Facebook();
facebookClient.authorize(this, "[APP ID]", new String[] {"publish_stream", "read_stream", "offline_access"}, this);

where "this" is an Activity that implements a DialogListener, and "[APP ID]" is my Facebook application ID.

其中“this”是一个实现DialogListener的Activity,“[APP ID]”是我的Facebook应用程序ID。

Thanks.

谢谢。

[UPDATE 2]

[更新 2]

I found a solution (see below), though the only thing missing is the ability to auto-populate the login text boxes with the data I have stored in the app. The official Facebook Android SDK may not allow for this. I'll keep looking into it.

我找到了一个解决方案(见下文),但唯一缺少的是使用我存储在应用程序中的数据自动填充登录文本框的能力。官方 Facebook Android SDK 可能不允许这样做。我会继续研究它。

采纳答案by RyanM

I figured it out, with Tom's help (thanks). The key was creating a dialog with the "stream.publish" API call, using the Facebook Android SDK. Here are the steps:

我想通了,在汤姆的帮助下(谢谢)。关键是使用 Facebook Android SDK 创建一个带有“stream.publish”API 调用的对话框。以下是步骤:

  1. Download the official Facebook Android SDK : http://github.com/facebook/facebook-android-sdk
  2. Import the project files into Eclipse.
  3. Export the project as a *.jar file. (this might cause a conflict)

    [UPDATE]

    Facebook recently updated the source code and I noticed the icon file caused resource id conflicts with my projects (Android 1.5+). My solution is to forget about exporting as a jar. Instead, copy the Facebook "com" folder directly into your app's "src" folder (i.e. "com.facebook.android" should be a package in your app... right alongside your source files). If you already have a "com" folder in your "src" folder, don't worry about any dialog boxes that appear about overwriting files, none of your source files should be overwritten. Go back into Eclipse, and refresh the "src" folder and "com.facebook.android" should now be listed as a package. Copy one of the included Facebook icons to your app's "drawable" folder and refresh that as well. Eclipse will complain about the "FbDialog.java" file... just add an import pointing to your app's "R" file to the header of that file (e.g. if your app's package name is "com.android.myapp," then add this: "import com.android.myapp.R;"). Go to #5 if you needed to do this.

  4. Add the .jar file to your project's build path

  5. Look at the following simplified example code:
  1. 下载官方 Facebook Android SDK:http: //github.com/facebook/facebook-android-sdk
  2. 将项目文件导入 Eclipse。
  3. 将项目导出为 *.jar 文件。(这可能会导致冲突)

    [更新]

    Facebook 最近更新了源代码,我注意到图标文件导致资源 ID 与我的项目(Android 1.5+)发生冲突。我的解决方案是忘记导出为 jar。相反,将 Facebook 的“com”文件夹直接复制到您的应用程序的“src”文件夹中(即“com.facebook.android”应该是您应用程序中的一个包...就在您的源文件旁边)。如果您的“src”文件夹中已经有一个“com”文件夹,请不要担心出现任何关于覆盖文件的对话框,您的任何源文件都不应该被覆盖。返回 Eclipse,刷新“src”文件夹,“com.facebook.android”现在应该作为一个包列出。将包含的 Facebook 图标之一复制到您的应用程序的“drawable”文件夹中并刷新它。Eclipse 会抱怨“FbDialog.java”文件......只需将指向您应用程序的“R”文件的导入添加到该文件的标题(例如,如果您的应用程序的包名称是“com.android.myapp”,然后添加这个:“导入com.android.myapp.R;”)。如果您需要这样做,请转到#5。

  4. 将 .jar 文件添加到项目的构建路径

  5. 看下面的简化示例代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import com.facebook.android.*;
import com.facebook.android.Facebook.DialogListener;

public class FacebookActivity extends Activity implements DialogListener,
        OnClickListener
{

    private Facebook facebookClient;
    private LinearLayout facebookButton;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.test);//my layout xml

        facebookButton = (LinearLayout)this.findViewById(R.id.Test_Facebook_Layout);

    }

    @Override
    public void onComplete(Bundle values)
    {

        if (values.isEmpty())
        {
            //"skip" clicked ?
            return;
        }

        // if facebookClient.authorize(...) was successful, this runs
        // this also runs after successful post
        // after posting, "post_id" is added to the values bundle
        // I use that to differentiate between a call from
        // faceBook.authorize(...) and a call from a successful post
        // is there a better way of doing this?
        if (!values.containsKey("post_id"))
        {
            try
            {
                Bundle parameters = new Bundle();
                parameters.putString("message", "this is a test");// the message to post to the wall
                facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
            }
            catch (Exception e)
            {
                // TODO: handle exception
                System.out.println(e.getMessage());
            }
        }
    }

    @Override
    public void onError(DialogError e)
    {
        System.out.println("Error: " + e.getMessage());
    }

    @Override
    public void onFacebookError(FacebookError e)
    {
        System.out.println("Error: " + e.getMessage());
    }

    @Override
    public void onCancel()
    {
    }

    @Override
    public void onClick(View v)
    {
        if (v == facebookButton)
        {
            facebookClient = new Facebook();
            // replace APP_API_ID with your own
            facebookClient.authorize(this, APP_API_ID,
                new String[] {"publish_stream", "read_stream", "offline_access"}, this);
        }
    }
}

回答by RyanM

Here is an objective answer to your new question, "What do I do next?"

这是对您的新问题“下一步我该怎么做?”的客观回答。

A quick look at the source code leads me to believe this is what you do:

快速查看源代码让我相信这就是你所做的:

Check this URL for the REST (http://en.wikipedia.org/wiki/Representational_State_Transfer) API methods you can use to leave a comment/post:

检查此 URL 以获取可用于发表评论/帖子的 REST ( http://en.wikipedia.org/wiki/Representational_State_Transfer) API 方法:

http://developers.facebook.com/docs/reference/rest/

http://developers.facebook.com/docs/reference/rest/

Specifically this: http://developers.facebook.com/docs/reference/rest/links.post

具体来说:http: //developers.facebook.com/docs/reference/rest/links.post

Check out lines 171 through 295 of Facebook.java http://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/android/Facebook.java

查看 Facebook.java http://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/android/Facebook.java 的第 171 至 295 行

To see how to use the API to make these requests.

了解如何使用 API 发出这些请求。

You'll probably want this method (it's overloaded, see the code).

您可能需要此方法(它已重载,请参阅代码)。

        /**
* Make a request to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
*
* See http://developers.facebook.com/docs/reference/rest/
*
* Note that this method blocks waiting for a network response, so do not
* call it in a UI thread.
*
* Example:
* <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* String response = request(parameters);
* </code>
*
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* @throws IOException
* if a network error occurs
* @throws MalformedURLException
* if accessing an invalid endpoint
* @throws IllegalArgumentException
* if one of the parameters is not "method"
* @return JSON string representation of the response
*/
    public String request(Bundle parameters) 

回答by Joakim Engstrom

To those who have problems, in the new facebook(); , the string is you App_id, and just delete the APP_ID in the authorized call.

对于那些有问题的人,在新的 facebook(); ,字符串就是你的App_id,把授权调用中的APP_ID删掉就行了。

Don't know why the error message is shown, but I guess that facebook updated the facebook SDK.

不知道为什么会显示错误消息,但我猜是 facebook 更新了 facebook SDK。

回答by Nilesh Gawade

AsyncFacebookRunner mAsyncRunner;
    Facebook    facebook =new Facebook("Your app id");

btnLogin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
                    @Override
                    public void onComplete(Bundle values) {



                    }

                    @Override
                    public void onFacebookError(FacebookError error) {
                    }

                    @Override
                    public void onError(DialogError e) {
                    }

                    @Override
                    public void onCancel() {
                    }
                });

            }
        });

    public void postOnWall(String msg) {
            Log.d("Tests", "Testing graph API wall post");
             try {
                    String response = facebook.request("me");
                    Bundle parameters = new Bundle();
                    parameters.putString("message", msg);
                    parameters.putString("description", "test test test");
                    response = facebook.request("me/feed", parameters, 
                            "POST");
                    Log.d("Tests", "got response: " + response);
                    if (response == null || response.equals("") || 
                            response.equals("false")) {
                       Log.v("Error", "Blank response");
                   }
             } catch(Exception e) {
                 e.printStackTrace();
             }