java - Facebook Connect Android——使用 stream.publish @ http ://api. facebook.com/restserver.php

标签 java android facebook

我收到以下错误:

<error_code>104</error_code>
<error_msg>Incorrect signature</error_msg>

我应该将 contentType 类型设置为什么?我应该设置为:

String contentType = "application/x-www-form-urlencoded";

String contentType = "multipart/form-data; boundary=" + kStringBoundary; 

这就是我编写流的方式:

HttpURLConnection conn = null;
OutputStream out = null;
InputStream in = null;
try {
    conn = (HttpURLConnection) _loadingURL.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    if (method != null) {
        conn.setRequestMethod(method);
        if ("POST".equals(method)) {
            //"application/x-www-form-urlencoded";
            String contentType = "multipart/form-data; boundary=" + kStringBoundary;
            //String contentType = "application/x-www-form-urlencoded";
            conn.setRequestProperty("Content-Type", contentType);
        }

        // Cookies are used in FBPermissionDialog and FBFeedDialog to
        // retrieve logged user
       conn.connect();
       out = conn.getOutputStream();
       if ("POST".equals(method)) {
            String body = generatePostBody(postParams);
            if (body != null) {
                out.write(body.getBytes("UTF-8"));
            }
        }
        in = conn.getInputStream();

这是我用来发布流的方法:

private void publishFeed(String themessage) {
    //Intent intent = new Intent(this, FBFeedActivity.class);
   // intent.putExtra("userMessagePrompt", themessage);
  //  intent.putExtra("attachment", 
    Map<String, String> getParams = new HashMap<String, String>();
    // getParams.put("display", "touch");
    // getParams.put("callback", "fbconnect://success");
    // getParams.put("cancel", "fbconnect://cancel");

     Map<String, String> postParams = new HashMap<String, String>();

     postParams.put("api_key", _session.getApiKey());
     postParams.put("method", "stream.publish");
     postParams.put("session_key", _session.getSessionKey());
     postParams.put("user_message", "TESTING 123");
    // postParams.put("preview", "1");
     postParams.put("attachment", "{\"name\":\"Facebook Connect for Android\",\"href\":\"http://code.google.com/p/fbconnect-android/\",\"caption\":\"Caption\",\"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}");
    // postParams.put("user_message_prompt", "22222");


     try {
         loadURL("http://api.facebook.com/restserver.php", "POST", getParams, postParams);
     } catch (MalformedURLException e) {
         e.printStackTrace();
     }
}

这是 generatePostBody() :

private String generatePostBody(Map<String, String> params) {
    StringBuilder body = new StringBuilder();
    StringBuilder endLine = new StringBuilder("\r\n--").append(kStringBoundary).append("\r\n");

    body.append("--").append(kStringBoundary).append("\r\n");

    for (Entry<String, String> entry : params.entrySet()) {
        body.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"\r\n\r\n");
        String value = entry.getValue();
        if ("user_message_prompt".equals(entry.getKey())) {
            body.append(value);
        }
        else {
            body.append(CcUtil.encode(value));
        }

        body.append(endLine);
    }

    return body.toString();
}

谢谢。

最佳答案

这来自 Facebook 开发者维基:http://wiki.developers.facebook.com/index.php/API

Note: If you manually form your HTTP POST requests to Facebook, you must include the request data in the POST body. In addition, you should include a Content-Type: header of application/x-www-form-urlencoded.

仅在上传文件时使用multipart/form-data(例如 Facebook API 上的 Photos.upload)

此外,基于此 API 引用,http://wiki.developers.facebook.com/index.php/How_Facebook_Authenticates_Your_Application ,这就是你做错的地方。

1) 不要使用HashMap 来存储Facebook 参数。参数必须按其键排序。而是使用 SortedMap 接口(interface)并使用 TreeMap 来存储 Facebook 参数。

2) 始终在将调用发送到 Facebook 之前在映射中包含 sig 参数。您收到“104 错误签名”,因为 Facebook 在您的请求中找不到 sig 参数。

引用资料 ( http://wiki.developers.facebook.com/index.php/How_Facebook_Authenticates_Your_Application ) 准确地展示了如何创建 facebook 使用的 MD5 签名。

以下是为 Facebook 快速创建 sig 值的方法。

String hashString = "";
        Map<String, String> sortedMap = null;
        if (parameters instanceof TreeMap) {
            sortedMap = (TreeMap<String, String>) parameters; 
        } else {
            sortedMap = new TreeMap<String, String>(parameters);
        }

        try {
            Iterator<String> iter = sortedMap.keySet().iterator();
            StringBuilder sb = new StringBuilder();
            synchronized (iter) {
                while (iter.hasNext()) {
                    String key = iter.next();
                    sb.append(key);
                    sb.append("=");
                    String value = sortedMap.get(key);
                    sb.append(value == null ? "" : value);
                }
            }
            sb.append(secret);

            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] digested = digest.digest(sb.toString().getBytes());

            BigInteger bigInt = new BigInteger(1, digested);
            hashString = bigInt.toString(16);
            while (hashString.length() < 32) {
                hashString = "0" + hashString;
            }
        } catch (NoSuchAlgorithmException nsae) {
            // TODO: handle exception
            logger.error(e.getLocalizedMessage(), e);
        }

        return hashString;

关于java - Facebook Connect Android——使用 stream.publish @ http ://api. facebook.com/restserver.php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2140952/

相关文章:

java - 如何在CameraSource上放置一个图标?

java - 我的 listview 代码有什么问题?

android - android 上 sqlite 中的关系表

android - 使用 Gson JSONObject 解析 JSON 包含 JSON 数组列表

java - 如何将signed_request参数获取到GWT MainEntryPoint客户端类中?

java - 模拟用户点击网页[JAVA]

java - 如何正确地将路径传递给 MediaPlayer(错误 java.net.URISyntaxException)

java - 自定义二叉搜索树中的最短路径

php - 您将如何使用 facebook php sdk 执行 `debug_token` 调用?

html - 在 iframe 或框架中打开 Facebook 页面?