laravel - How to call API from controller Laravel without using curl and guzzle as its not working
问题描述
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?
I used curl but it is always giving me a false response.
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.
解决方案
Laravel 7.x 和 8.x 的更新。现在我们可以使用内置的 Http(Guzzle HTTP) 客户端了。
文档:: https://laravel.com/docs/8.x/http-client#making-requests
use Illuminate\Support\Facades\Http;
$response = Http::get('https://jsonplaceholder.typicode.com/posts');
$response = Http::post('https://jsonplaceholder.typicode.com/posts', [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
]);
$response = Http::withHeaders([
'Authorization' => 'token'
])->post('http://example.com/users', [
'name' => 'Akash'
]);
$response->body() : string;
$response->json() : array|mixed;
$response->object() : object;
$response->collect() : Illuminate\Support\Collection;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
对于 Laravel < 7,你需要安装 Guzzle 包
文档:https ://docs.guzzlephp.org/en/stable/index.html
安装
composer require guzzlehttp/guzzle
得到
$client = new \GuzzleHttp\Client();
$response = $client->get('https://jsonplaceholder.typicode.com/posts');
return $response;
邮政
$client = new \GuzzleHttp\Client();
$body = [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
];
$response = $client->post('https://jsonplaceholder.typicode.com/posts', ['form_params' => $body]);
return $response;
一些有用的方法
$response->getStatusCode();
$response->getHeaderLine('content-type');
$response->getBody();
- 我们还可以添加标题
$header = ['Authorization' => 'token'];
$client = new \GuzzleHttp\Client();
$response = $client->get('example.com', ['headers' => $header]);
此方法的助手
我们可以为这些方法创建一个通用助手。
- 在 app 文件夹中创建 Helpers 文件夹
app\Helpers
- 然后在 Helpers 文件夹中创建一个文件 Http.php
app\Helpers\Http.php
- 在 Http.php 中添加此代码
<?php
namespace App\Helpers;
use GuzzleHttp;
class Http
{
public static function get($url)
{
$client = new GuzzleHttp\Client();
$response = $client->get($url);
return $response;
}
public static function post($url,$body) {
$client = new GuzzleHttp\Client();
$response = $client->post($url, ['form_params' => $body]);
return $response;
}
}
- 现在在控制器中你可以使用这个助手。
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use App\Helpers\Http;
class Controller extends BaseController
{
/* ------------------------ Using Custom Http Helper ------------------------ */
public function getPosts()
{
$data = Http::get('https://jsonplaceholder.typicode.com/posts');
$posts = json_decode($data->getBody()->getContents());
dd($posts);
}
public function addPost()
{
$data = Http::post('https://jsonplaceholder.typicode.com/posts', [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
]);
$post = json_decode($data->getBody()->getContents());
dd($post);
}
}
没有助手
- 在主控制器中,我们可以创建这些功能
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
public function get($url)
{
$client = new GuzzleHttp\Client();
$response = $client->get($url);
return $response;
}
public function post($url,$body) {
$client = new GuzzleHttp\Client();
$response = $client->post($url, ['form_params' => $body]);
return $response;
}
}
- 现在在控制器中我们可以调用
<?php
namespace App\Http\Controllers;
class PostController extends Controller
{
public function getPosts()
{
$data = $this->get('https://jsonplaceholder.typicode.com/posts');
$posts = json_decode($data->getBody()->getContents());
dd($posts);
}
public function addPost()
{
$data = $this->post('https://jsonplaceholder.typicode.com/posts', [
'title' => 'foo',
'body' => 'bar',
'userId' => 1
]);
$post = json_decode($data->getBody()->getContents());
dd($post);
}
}
推荐阅读
- jekyll - 修改现有的 Jekyll 主题以拥有静态主页
- android - Android webView setUserAgentString 影响视频流
- ios - 如何解决颤振项目中的 Firebase 身份验证 Pod 错误?
- python - Python 交叉或切换公式
- python - Python:从 x 轴上的数据框绘制日期时间并格式化 x 轴
- java - 如何在 Android WebView 中隐藏进度条
- excel - 搜索字符串并返回行号 VBA
- css - 希望菜单和子菜单在悬停时的行为相同 - 当前项目的问题
- java - 一旦我按下后退按钮,片段中的 MapBox 也遇到了 permissionsManager.requestLocationPermissions(this) 的问题
- php - Laravel artisan 命令使用端口 33060 但数据库停止工作