首页 > 解决方案 > 标头的 Guzzle OAuth 1.0 问题,401 错误请求

问题描述

我正在尝试将我自己的 cURL 代码替换为 Guzzle 客户端,但由于某种原因我无法让它工作,这是 cURL 请求并且非常好:

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $this->method,
            CURLOPT_HTTPHEADER => array(
                'Authorization: OAuth realm="' . $this->realm . '",oauth_consumer_key="' . $this->consumerkey . '",oauth_token="' . $this->tokenid . '",oauth_signature_method="HMAC-SHA256",oauth_timestamp="' . $this->timestamp . '",oauth_nonce="' . $this->nonce . '",oauth_version="1.0",oauth_signature="' . $this->signature . '"',
                'Cookie: NS_ROUTING_VERSION=LAGGING'
            ),
        ));

将其替换为:

        $this->headers['Authorization'] = 'OAuth realm="' . $this->realm . '";oauth_consumer_key="' . $this->consumerkey . '";oauth_token="' . $this->tokenid . '";oauth_signature_method="HMAC-SHA256";oauth_timestamp="' . $this->timestamp . '";oauth_nonce="' . $this->nonce . '";oauth_version="1.0";oauth_signature="' . $this->signature . '"';
        $this->headers['Cookie'] = 'NS_ROUTING_VERSION=LAGGING';

        $request = new Request($type, $method, ['headers' => $this->headers], $body);

我得到的响应是 401 bad request,表示授权无效。

有谁知道如何解决?非常感激。

标签: guzzle

解决方案


你可以这样试试。

use GuzzleHttp\Psr7\Request;


$client = new \GuzzleHttp\Client();
$headers['Authorization'] = 'OAuth realm="' . $this->realm . '";oauth_consumer_key="' . $this->consumerkey . '";oauth_token="' . $this->tokenid . '";oauth_signature_method="HMAC-SHA256";oauth_timestamp="' . $this->timestamp . '";oauth_nonce="' . $this->nonce . '";oauth_version="1.0";oauth_signature="' . $this->signature . '"';
$headers['Cookie'] = "NS_ROUTING_VERSION=LAGGING";
$response = $client->request('YOUR HTTP METHOD HERE', 'YOUR URL', );
$request = new Request('YOUR HTTP METHOD HERE', 'YOUR URL');
$response = $client->send($request, 
              ['headers' => $headers,
               'body'    => $body, //should be array
              ]);
print_r($response);

推荐阅读