簡體   English   中英

將媒體上傳到 twitter API

[英]uploading media to the twitter API

我正在嘗試通過 API 將媒體上傳到 Twitter,但我不斷收到“錯誤請求”錯誤

HTTP request failed! HTTP/1.1 400 Bad Request

這是我的電話

$image = 'http://4.bp.blogspot.com/-JOqxgp-ZWe0/U3BtyEQlEiI/AAAAAAAAOfg/Doq6Q2MwIKA/s1600/google-logo-874x288.png';

$media_ids = $twitterService->request('https://upload.twitter.com/1.1/media/upload.json', 'POST', array(
    'media' => $image
));

我正在使用 oauth 進行身份驗證,並且任何其他類型的請求似乎都有效,例如獲取用戶時間表。

我還在使用庫 - https://github.com/Lusitanian/PHPoAuthLib - 它為我附加了諸如 oauth 令牌之類的東西。 有任何想法嗎?

編輯:

我還嘗試使用 base64 圖像發出相同的請求,如下所示:

$path = '../uploads/0PQ4j0yfMl1420641234.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

$media_ids = $twitterService->request('https://upload.twitter.com/1.1/media/upload.json', 'POST',     array(
        'media_data' => $base64
    ));

並通過抓取原始圖像

$image = file_get_contents($path);

$media_ids = $twitterService->request('https://upload.twitter.com/1.1/media/upload.json', 'POST', array(
        'media' => $image
    ));

正如文檔所說 - 圖像應該是圖像的 base64 編碼字節,而不是圖像的 URL。

對於圖片網址,您可以執行以下操作

$image = 'http://4.bp.blogspot.com/-JOqxgp-ZWe0/U3BtyEQlEiI/AAAAAAAAOfg/Doq6Q2MwIKA/s1600/google-logo-874x288.png';

$file = '/tmp/file';
file_put_contents($file, file_get_contents($image));
$media = $connection->upload('media/upload', ['media' => $file]);

我無法在任何地方找到答案,但我設法通過首先上傳媒體而不將 api 版本設置為 2 來解決它。但在檢索圖像后立即設置 api 版本。

似乎版本 2 的端點還不完全支持媒體上傳,不知道為什么。 但這對我來說是完美的,希望它對某人有用:

$connection = new TwitterOAuth(env('TWITTER_CONSUMER_KEY'), env('TWITTER_CONSUMER_SECRET'), env('TWITTER_ACCESS_TOKEN'), env('TWITTER_ACCESS_TOKEN_SECRET'));

    $result = $connection->upload('media/upload', [
        'media' => '/img/path.png',
    ], true);

    // check here to see if img has uploaded
    var_dump($result);

    $connection->setApiVersion('2');

    $response = $connection->post('tweets', [
        'text' => 'Test',
        'media' => [
            'media_ids' => [$result->media_id_string],
        ]
    ], true);

    var_dump($response);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM