简体   繁体   中英

Twitter Streaming 401 Unauthorized OAuth

I'm trying to create a script that uses the twitter streaming api to keep a tab on tweets with a certain hash-tag.

Whenever I try creating a request though, I always get a 401 Unauthorized return. Can anyone help me figure out what I'm doing incorrectly?

I tried to follow twitter's api to the dot, but apparently I'm doing something wrong. The code I have is below.

$base_url_string = urlencode($base_url);
$parameter_string = urlencode('oauth_consumer_key') . '=' . urlencode($consumer_key) . '&'
    . urlencode('oauth_nonce') . '=' . urlencode($nonce) . '&'
    . urlencode('oauth_signature_method') . '=' . urlencode($signature_method) . '&'
    . urlencode('oauth_timestamp') . '=' . urlencode($timestamp) . '&'
    . urlencode('oauth_token') . '=' . urlencode($token) . '&'
    . urlencode('oauth_version') . '=' . urlencode($version) . '&'
    . urlencode('track') . '=' . urlencode('#kitten');


$signature_base_string = $method . "&" . $base_url_string . "&" . urlencode($parameter_string);

$signature = base64_encode(hash_hmac('sha1', $signature_base_string, $secret, true));

$fp = fsockopen("ssl://stream.twitter.com", 443, $errno, $errstr, 30);

if (!$fp) {

    print "$errstr ($errno)\n";

} else {

$request = $method . " /1.1/statuses/filter.json?" . urlencode("track") . "=" . urlencode("#kitten") . " HTTP/1.1\r\n";
$request .= "Host: stream.twitter.com\r\n";
$request .= 'Authorization: OAuth'
        . ' oauth_consumer_key="' . $consumer_key . '",'
        . ' oauth_nonce="' . $nonce . '",'
        . ' oauth_signature="' . $signature . '",'
        . ' oauth_signature_method="' . $signature_method . '",'
        . ' oauth_timestamp="' . $timestamp . '",'
        . ' oauth_token="' . $token . '",'
        . ' oauth_version="' . $version . '"'
        . "\r\n\r\n";

print $request . "</br>";

fwrite($fp, $request);

while (!feof($fp)) {

    $json = fgets($fp);
    echo $json;
    $data = json_decode($json, true);

    if ($data) {

        print $data;
    }
}

print 'exiting...';
  fclose($fp);
}

Ok so I figured this all out. It was a combination of poor string manipulation and not Percent Encoding everything. Both the keys and values of the OAuth string must be Percent encoded. I had done that in the signature, but not in the actual request. Once I fixed that, the request got through and I was connected to the Twitter Streaming API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM