Qt5 http发布到Facebook失败了

时间:2015-02-28 15:10:55

标签: facebook qt facebook-graph-api

我是QT5的新手。

我尝试在QT5中使用我的access_token编写一个可以在Facebook上发帖的程序。

以下是我的代码段

功能用来做http post:

bool MainWindow::postRequest(QString link, QMap<QString, QString> data)
{
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);

    QUrl url(link);
    QNetworkRequest request(url);

    request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data");
    request.setHeader(QNetworkRequest::UserAgentHeader,"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36");
    QUrlQuery params;
    QByteArray postData;
    QStringList keys = data.keys();
    for(int i = 0; i < keys.size(); i++)
    {
        params.addQueryItem(keys[i],data[keys[i]]);
    }
    postData.append(params.toString());
    qDebug() << QString(postData);
    QObject::connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(replyFinished(QNetworkReply *)));

    QNetworkReply *reply = manager->post(request, postData);
    if(reply->error() != QNetworkReply::NoError)
        return false;
    return true;
}

当点击一个按钮时,我调用下面的函数:

void MainWindow::likeAct()
{
    QString postid = ui->postid->text(); //The id of my post
    QString token = ui->token->text(); //My access_token which had full permission
    QMap<QString,QString> data;
    data.insert("access_token",token);
        postRequest(QString("https://graph.facebook.com/v2.1/%1/likes").arg(postid),data);
}

replyFinished函数如下:

void MainWindow::replyFinished(QNetworkReply *reply)
{
    if(reply->error() != QNetworkReply::NoError)
    {
        qDebug() << "ERROR: " << reply->errorString();
    }
    else
    {
        QByteArray responseData = reply->readAll();
        QString qstr(responseData);
        qDebug() << "SUCCESS: " << qstr;
    }
}

回复印刷的qDebug():

ERROR:  "Error downloading https://graph.facebook.com/v2.1/1041840172497418/likes - server replied: Forbidden"

请帮帮我

1 个答案:

答案 0 :(得分:0)

您的帐户没有足够的权限进行上传。当授权Facebook正在进行时,请检查'范围'参数(对于API&gt; 2.0,还需要'publish_actions'权限):

QUrl CFacebookUrl::facebookLoginUrl() const
{
  QUrl url( baseUrl( buAuthorization ) );//https://www.facebook.com/dialog/oauth
  {
    QUrlQuery query;
    query.addQueryItem( "client_id", "your_client_id" );
    query.addQueryItem( "redirect_uri", "your_redirect" );
    query.addQueryItem( "response_type", "code" );
    query.addQueryItem( "display", "page" );
    query.addQueryItem( "scope", "read_stream,publish_stream,publish_actions,user_photos" );
    url.setQuery( query );
  }
  return url;
}