我一直在尝试在Twitter上使用Twitter API的仅应用程序身份验证。当我运行我的代码时,我收到此错误:
Failure "Error transferring https://api.twitter.com/oauth2/token - server replied: Forbidden"
这是我的请求代码:
QJsonObject params;
params.insert("grant_type","client_credentials");
QUrl url("https://api.twitter.com/oauth2/token");
QNetworkRequest request;
request.setUrl(url);
QString authorizationKey = m_consumerKey + ":" + m_consumerSecret;
QByteArray encryptedAuth = authorizationKey.toUtf8().toBase64();
request.setRawHeader("User-Agent", "My App v1.0.0");
request.setRawHeader("Authorization", "Basic "+ encryptedAuth);
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.setSslConfiguration(QSslConfiguration::defaultConfiguration());
QNetworkReply* reply = m_networkManager->post(request, QJsonDocument(params).toJson());
也许我错过了什么?
答案 0 :(得分:1)
我能够解决这个问题。事实证明,我正在为请求正文发送错误的格式。我改变了:
QJsonObject params;
params.insert("grant_type","client_credentials");
...
QNetworkReply* reply = m_networkManager->post(request, QJsonDocument(params).toJson());
为:
QUrlQuery payload;
payload.addQueryItem("grant_type","client_credentials");
QByteArray postData = payload.query(QUrl::FullyEncoded).toUtf8();
...
QNetworkReply* reply = m_networkManager->post(request, postData);