使用laravel中的助手从控制器调用API的最佳实践是什么?
我需要从其他控制器调用serval API,所以I need a helper for this
最好。
我使用了curl,但是它总是给我一个错误的答复。
答案 0 :(得分:4)
您可以使用Guzzle pacakge docs:https://github.com/guzzle/guzzle
composer require guzzlehttp/guzzle
$client = new \GuzzleHttp\Client();
$request = $client->get('example.com');
$response = $request->getBody();
return $response;
$client = new \GuzzleHttp\Client();
$body['name'] = "Testing";
$url = "http://my-domain.com/api/v1/post";
$response = $client->createRequest("POST", $url, ['body'=>$body]);
$response = $client->send($response);
return $response;
$response->getStatusCode(); # 200
$response->getHeaderLine('content-type'); # 'application/json; charset=utf8'
$response->getBody(); # '{"id": 1420053, "name": "guzzle", ...}'
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
$header = array('Authorization'=>'token');
$client = new \GuzzleHttp\Client();
$request = $client->get('example.com',array('headers' => $header));
$response = $request->getBody();
我们可以为这些方法创建一个公共帮助器。 *首先在应用程序文件夹中创建文件夹
app\Helper
app\Helper\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->createRequest("POST", $url, ['body'=>$body]);
$response = $client->send($response);
return $response;
}
}
use App\Helper\Helper;
Helper::GetApi('ultimateakash.com');
<?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->createRequest("POST", $url, ['body'=>$body]);
$response = $client->send($response);
return $response;
}
}
$this->GetApi('ultimateakash.com');