如何从外部API网址获取数据

时间:2019-07-10 06:22:29

标签: laravel api guzzle

我正在使用laravel v5.8.17,但我从此端某处获得了此代码,但是我的代码无法正常工作,我只能获取状态代码200,但无法返回响应(正文和标头) ,我这样尝试过:(在控制器上)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use GuzzleHttp\Client;

class yourController extends Controller
{
    public function saveApiData(){

    if(isset($_res['https://my_api_url'])){
            require './vendor/autoload.php';  

    $client = new GuzzleHttp\Client();
        $res = $client->request('POST', 'https://my_api_url', [
            'formData' => [

             'email' => 'myemail',
             'password' => 'mypassword',            

    ] ]);

        echo $res->getStatusCode();
        //200

        echo $res->getHeader('content-type');
        //'application/json; charset=utf8'

        echo $res->getBody();
        // "type":"User"...'    

    }   

    }       
}

1 个答案:

答案 0 :(得分:0)

尝试使它像这样:

print_r(json_decode($response->getBody()->getContents()));exit(0);