PHP发送带有标题的HTTPS休息请求

时间:2019-06-17 21:52:09

标签: php rest api yii2 request

我需要使用auth标头向api发送请求

这是我到目前为止尝试过的

$client = new \yii\httpclient\Client(['baseUrl' => 'https://link']);
$response = $client->createRequest()
            ->setMethod('GET')
            ->addHeaders(['authorization' => 'token'])
            ->send();
var_dump($response);
//other
$client = new \GuzzleHttp\Client();
$headers = ['authorization' => 'token'];
$body = 'Hello!';
$request = new \GuzzleHttp\Psr7\Request('GET', 'https://link', $headers, $body);
$response = $client->send($request, ['timeout' => 2]);
$curl = new \linslin\yii2\curl\Curl();

$response = $curl->setHeaders($headers)->get('link', $headers);
var_dump($response);

// other
$opts = [
    "http" => [
        "method" => "GET",
        "header" => "authorization:token\r\n",
    ],
];

$context = stream_context_create($opts);

$file = file_get_contents('link', false, $context);
var_dump($file);

// other
$ch = curl_init();
$headers = ["authorization:token"];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); # custom headers, see above
$result = curl_exec($ch); # run!
// curl_close($ch);
var_dump($result);

ps:我正在使用yii2框架

那么谁能告诉我是怎么回事?

{
    "client": {
        "baseUrl": null,
        "formatters": {
            "urlencoded": {
                "encodingType": 1,
                "charset": null
            }
        },
        "parsers": [],
        "requestConfig": [],
        "responseConfig": {
            "format": "json"
        },
        "contentLoggingMaxSize": 2000
    }
}

那是我得到的错误。我没有有关连接的任何详细信息...

1 个答案:

答案 0 :(得分:0)

这对我有用

$client = new \yii\httpclient\Client(['responseConfig' => [
            'format' => \yii\httpclient\Client::FORMAT_JSON,
        ]]);
        $response = $client->createRequest()
            ->setHeaders(['authorization' => 'f52d76cc976e0e1b6aa81c926cbc33823b5e5983', 'content-type' => 'application/json'])
            ->setMethod('GET')
            ->setUrl('https://preprod-next-ngcvin5.ngc-data.fr/api/v1/vehicules/CR-157-NB')
            ->send();

        return $response->data;
相关问题