【发布时间】:2022-02-11 16:22:43
【问题描述】:
我正在尝试使用 Twitter API v2 发布推文,但出现错误。我正在使用 TwitterAPIExchange.php 库,当我尝试使用 GET 搜索推文时,它可以正常工作。但是 POST 不走运,请参阅下面的代码以及来自 Twitter 的管理推文文档:https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets
也许我在结束点之后遗漏了一些参数。
header('Content-Type:application/json');
include ($_SERVER["DOCUMENT_ROOT"] . "/TwitterAPIExchange.php");
$settings = array(
'oauth_access_token' => "xxxx",
'oauth_access_token_secret' => "xxxx",
'consumer_key' => "xxxx",
'consumer_secret' => "xxxx"
);
$url = "https://api.twitter.com/2/tweets";
$requestMethod = 'POST';
$postfields = array('status' => 'This is the text to Tweet');
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest();
错误:
{
errors: [
{
parameters: { },
message: "Requests with bodies must have content-type of application/json."
}
],
title: "Invalid Request",
detail: "One or more parameters to your request was invalid.",
type: "https://api.twitter.com/2/problems/invalid-request"
}
【问题讨论】:
-
错误信息告诉你添加header Content-Type: application/json
-
谢谢,代码中的标头不正确吗?
-
不,当然不是 - 为 your 脚本的响应设置 Content-Type 标头,它与发送的内容无关对 twitter API 的请求。您需要去检查您在那里使用的库是否支持在某处为 API 请求指定 Content-Type。