使用 php Http_request 进行 Twitter 授权

发布于 2024-12-11 17:10:34 字数 4215 浏览 0 评论 0原文

我真的需要你的帮助。

我正在尝试使用 php 不使用 cURL 从 twitter 获取请求令牌。

我的第一次尝试是使用 fsockopen。

$fp = fsockopen("ssl://api.twitter.com", 443) or die ("unable to open socket");

然后,我制作了 HTTP POST 标头,如下所示。

$auth = "oauth_callback="http%3A%2F%2Fmydomain.org%2F~myID%2Ftwt-oauth%2Fcallback.php", oauth_consumer_key="ExmfrhvgMkUmwzGKCg5FQw", oauth_nonce="da4dfa747b27d83c9bbda69452a87bee", oauth_signature="L9ucYZUfKQ%2BRkp1FQNbzEXXrl1w%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1319451330", oauth_version="1.0" ";


$msg = "POST /oauth/request_token HTTP/1.1 \r\n";
$msg .= "Host: api.twitter.com \r\n";
$msg .= "Authorization: Oauth " . $auth . "\r\n";
$msg .= "Connection:Keep-Alive \r\n\r\n";
$bytes = fwrite($fp, $msg);

结果是

HTTP/1.1 401 Unauthorized
Date: Mon, 24 Oct 2011 10:15:30 GMT
Server: hi
Status: 401 Unauthorized
X-Transaction: 1319451330-75511-27215
X-Frame-Options: SAMEORIGIN
Last-Modified: Mon, 24 Oct 2011 10:15:30 GMT
X-Runtime: 0.00602
Content-Type: text/html; charset=utf-8
Content-Length: 44
Pragma: no-cache
X-Content-Type-Options: nosniff
X-Revision: DEV
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
X-MID: 6301c02e82f43071b60e91cc31326d5354818c83
Set-Cookie: k=143.248.234.102.1319451330738600; path=/; expires=Mon, 31-Oct-11 10:15:30 GMT; domain=.twitter.com
Set-Cookie: guest_id=v1%3A131945133074814112; domain=.twitter.com; path=/; expires=Wed, 23-Oct-2013 22:15:30 GMT
Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCL2IbTUzAToHaWQiJWEyZDlhNjMzYWJmMmNh%250ANmE2NDU1OTMyMzQ2MWY4MTkxIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--f5d5dc205f414bd74c0270e9610712ad1e04d2ee; domain=.twitter.com; path=/; HttpOnly
Vary: Accept-Encoding
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive

Failed to validate oauth signature and token

我不知道为什么......我需要base64_encode还是urlencode $auth? (那么,如何?)
上面 $auth 的值是我从日志中复制并粘贴的值。 (“”可能有问题吗?)

然后我尝试了 Http_request 非常简单。

$httpReq = new HTTP_Request("https://api.twitter.com/oauth/request_token");
$httpReq->setMethod(HTTP_REQUEST_METHOD_POST);
$httpReq->addHeader("Authorization", $auth);
$res = $httpReq->sendRequest();

那么,$res->getMessage() 是“无法验证 oauth 签名和令牌” 与上面的第一次尝试相同。

有什么问题吗?

我被困在这里很长一段时间...真的需要帮助..

我添加了 cURL 使用版本的代码..我想要相同的结果...

  function http($url, $method, $postfields = NULL) {

//
    $this->http_info = array();
    $ci = curl_init();
    // Curl settings 
    curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
    curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
    curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
    curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
    curl_setopt($ci, CURLOPT_HEADER, FALSE);

    switch ($method) {
      case 'POST':
        curl_setopt($ci, CURLOPT_POST, TRUE);
        if (!empty($postfields)) {
          curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
        }    
        break;
      case 'DELETE':
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
        if (!empty($postfields)) {
          $url = "{$url}?{$postfields}";
        }    
    }    

    curl_setopt($ci, CURLOPT_URL, $url);
    $response = curl_exec($ci);
    $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
    $this->url = $url;
    curl_close ($ci);
    //   

    return $response;
  }

  /**  
   * Get the header info to store.
   */
  function getHeader($ch, $header) {
    $i = strpos($header, ':');
    if (!empty($i)) {
      $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
      $value = trim(substr($header, $i + 2)); 
      $this->http_header[$key] = $value;
    }    
    return strlen($header);
  }

i really need your help.

I'm trying to get request token from twitter with php NOT using cURL.

my first try was using fsockopen.

$fp = fsockopen("ssl://api.twitter.com", 443) or die ("unable to open socket");

then, i made HTTP POST header as below.

$auth = "oauth_callback="http%3A%2F%2Fmydomain.org%2F~myID%2Ftwt-oauth%2Fcallback.php", oauth_consumer_key="ExmfrhvgMkUmwzGKCg5FQw", oauth_nonce="da4dfa747b27d83c9bbda69452a87bee", oauth_signature="L9ucYZUfKQ%2BRkp1FQNbzEXXrl1w%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1319451330", oauth_version="1.0" ";


$msg = "POST /oauth/request_token HTTP/1.1 \r\n";
$msg .= "Host: api.twitter.com \r\n";
$msg .= "Authorization: Oauth " . $auth . "\r\n";
$msg .= "Connection:Keep-Alive \r\n\r\n";
$bytes = fwrite($fp, $msg);

the result was

HTTP/1.1 401 Unauthorized
Date: Mon, 24 Oct 2011 10:15:30 GMT
Server: hi
Status: 401 Unauthorized
X-Transaction: 1319451330-75511-27215
X-Frame-Options: SAMEORIGIN
Last-Modified: Mon, 24 Oct 2011 10:15:30 GMT
X-Runtime: 0.00602
Content-Type: text/html; charset=utf-8
Content-Length: 44
Pragma: no-cache
X-Content-Type-Options: nosniff
X-Revision: DEV
Expires: Tue, 31 Mar 1981 05:00:00 GMT
Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
X-MID: 6301c02e82f43071b60e91cc31326d5354818c83
Set-Cookie: k=143.248.234.102.1319451330738600; path=/; expires=Mon, 31-Oct-11 10:15:30 GMT; domain=.twitter.com
Set-Cookie: guest_id=v1%3A131945133074814112; domain=.twitter.com; path=/; expires=Wed, 23-Oct-2013 22:15:30 GMT
Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCL2IbTUzAToHaWQiJWEyZDlhNjMzYWJmMmNh%250ANmE2NDU1OTMyMzQ2MWY4MTkxIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--f5d5dc205f414bd74c0270e9610712ad1e04d2ee; domain=.twitter.com; path=/; HttpOnly
Vary: Accept-Encoding
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive

Failed to validate oauth signature and token

i don't know why... do i need to base64_encode or urlencode $auth? (then, how?)
value of $auth above is what i copied and pasted from log. (is it possible to have problem with quot "" ?)

i tried Http_request quite simple, then.

$httpReq = new HTTP_Request("https://api.twitter.com/oauth/request_token");
$httpReq->setMethod(HTTP_REQUEST_METHOD_POST);
$httpReq->addHeader("Authorization", $auth);
$res = $httpReq->sendRequest();

then, $res->getMessage() is "Failed to validate oauth signature and token"
the same as the first try above.

what's the problem?

i'm stuck here quite long time... really need help..

i added code of cURL-used version.. i want the same result of it...

  function http($url, $method, $postfields = NULL) {

//
    $this->http_info = array();
    $ci = curl_init();
    // Curl settings 
    curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
    curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
    curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
    curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
    curl_setopt($ci, CURLOPT_HEADER, FALSE);

    switch ($method) {
      case 'POST':
        curl_setopt($ci, CURLOPT_POST, TRUE);
        if (!empty($postfields)) {
          curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
        }    
        break;
      case 'DELETE':
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
        if (!empty($postfields)) {
          $url = "{$url}?{$postfields}";
        }    
    }    

    curl_setopt($ci, CURLOPT_URL, $url);
    $response = curl_exec($ci);
    $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
    $this->url = $url;
    curl_close ($ci);
    //   

    return $response;
  }

  /**  
   * Get the header info to store.
   */
  function getHeader($ch, $header) {
    $i = strpos($header, ':');
    if (!empty($i)) {
      $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
      $value = trim(substr($header, $i + 2)); 
      $this->http_header[$key] = $value;
    }    
    return strlen($header);
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷…雨湿花 2024-12-18 17:10:34

看看使用 我的 HTTP 请求类,它使用 fsockopen() - 它经过了彻底的尝试和测试(由我)。目前不支持 Oauth,但您应该能够使用 HTTPRequest::setRequestHeader() 手动设置标头。如果您安装了本机 HTTPRequest 类,您可能需要重命名该类 - 我最初编写它是为了在 PHP4 环境中使用,在该环境中我没有流支持,也无法控制已安装的扩展。

记录在文件顶部的注释中。

See if you get anywhere using my HTTP request class, which uses fsockopen() - it is thoroughly tried and tested (by me). Does not currently have native support for Oauth, but you should be able to set the header manually with HTTPRequest::setRequestHeader(). You may need to rename the class if you have the native HTTPRequest class installed - I originally wrote it for use in a PHP4 environment where I had no stream support and no control over the installed extensions.

Documented in comments at the top of the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文