如何在不使用 curl 和 guzzle 的情况下从控制器 Laravel 调用 API,因为它不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56071154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:20:20  来源:igfitidea点击:

How to call API from controller Laravel without using curl and guzzle as its not working

laravelapilaravel-5guzzle

提问by Mahendra Pratap

How to call an API from a controller using a helper in laravel without using curl and guzzle because both returing nothing. I have tested in postman the api is working fine but not in laravel. I need to call several API's from different controllers so what would be a good way to do this? Should i build a helper?

如何使用 Laravel 中的帮助程序从控制器调用 API,而不使用 curl 和 guzzle,因为两者都没有返回任何内容。我已经在邮递员中测试过,api 工作正常,但在 laravel 中却没有。我需要从不同的控制器调用多个 API,那么这样做的好方法是什么?我应该建立一个助手吗?

I used curl but it is always giving me a false response.

我使用 curl 但它总是给我错误的响应。

EDIT:

编辑:

I am looking for a reliable way to make api calls to various url's without having to rewrite the sending and receiving code for each api I want to use. Preferably a solution that implements "dry" (don't repeat yourself) principles and would serve as a base for any api specific logic, (parsing the response /translating for a model). That stuff would extend this base.

我正在寻找一种可靠的方法来对各种 url 进行 api 调用,而不必为我想要使用的每个 api 重写发送和接收代码。最好是一个实现“干”(不要重复自己)原则的解决方案,并将作为任何 api 特定逻辑的基础,(解析响应/翻译模型)。那东西会扩展这个基础。

回答by Akash Kumar Verma

you can use Guzzle pacakge docs: https://github.com/guzzle/guzzle

您可以使用 Guzzle pacakge 文档:https: //github.com/guzzle/guzzle

installation

安装

composer require guzzlehttp/guzzle

GET

得到

    $client = new \GuzzleHttp\Client();
    $request = $client->get('example.com');
    $response = $request->getBody();
    return $response;

POST

邮政

    $client = new \GuzzleHttp\Client();
    $body['name'] = "Testing";
    $url = "http://my-domain.com/api/v1/post";
    $response = $client->request("POST", $url, ['form_params'=>$body]);
    $response = $client->send($response);
    return $response;

Some Usefull Methods

一些有用的方法

    $response->getStatusCode(); # 200
    $response->getHeaderLine('content-type'); # 'application/json; charset=utf8'
    $response->getBody(); # '{"id": 1420053, "name": "guzzle", ...}'
  • We can also send asynchronous request
  • 我们也可以发送异步请求
    $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
    $promise = $client->sendAsync($request)->then(function ($response) {
        echo 'I completed! ' . $response->getBody();
    });
    $promise->wait();
  • we can also add headers
  • 我们还可以添加标题
    $header = array('Authorization'=>'token');
    $client = new \GuzzleHttp\Client();
    $request = $client->get('example.com',array('headers' => $header));
    $response = $request->getBody();

Helper For this Method

此方法的助手

we can create a common helper for these methods.

我们可以为这些方法创建一个通用的助手。

  • firstly create folder in app folder
  • 首先在app文件夹中创建文件夹
    app\Helper
  • then create a file inside Helper folder
  • 然后在 Helper 文件夹中创建一个文件
    app\Helper\Helper.php
  • add this code in Helper.php
  • 在 Helper.php 中添加此代码
<?php 

namespace App\Helper;
class Helper
{

    public static function GetApi($url)
    {
        $client = new \GuzzleHttp\Client();
        $request = $client->get($url);
        $response = $request->getBody();
        return $response;
    }


    public static function PostApi($url,$body) {
        $client = new \GuzzleHttp\Client();
        $response = $client->request("POST", $url, ['form_params'=>$body]);
        $response = $client->send($response);
        return $response;
    }
}

  • Now in controller use
  • 现在在控制器使用
    use App\Helper\Helper;
    Helper::GetApi('ultimateakash.com');

We can also do this without helper

我们也可以在没有帮手的情况下做到这一点

  • In Main controller we can create these functions
  • 在主控制器中,我们可以创建这些功能
<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function GetApi($url)
    {
        $client = new \GuzzleHttp\Client();
        $request = $client->get($url);
        $response = $request->getBody();
        return $response;
    }


    public function PostApi($url,$body) {
        $client = new \GuzzleHttp\Client();
        $response = $client->request("POST", $url, ['form_params'=>$body]);
        $response = $client->send($response);
        return $response;
    }
}
  • Now in controllers we can call
  • 现在在控制器中我们可以调用
    $this->GetApi('ultimateakash.com');