我想要的是从一个带有HTTP(例如,jQuery 的AJAX)请求的API 到一个外部api 的对象。我该如何开始?我对 Google 先生进行了研究,但找不到任何帮助。
我开始怀疑这是否可能?在这篇文章 Laravel 4 make post request from controller to external url with data 中,它看起来可以完成。但是没有示例,也没有任何来源可以找到一些文档。
请帮帮我?
基于此处对类似问题的回答:https://stackoverflow.com/a/22695523/1412268
看看Guzzle
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' => ['user', 'pass']]);
echo $res->getStatusCode(); // 200
echo $res->getBody(); // { "type": "User", ....
我们可以在 Laravel 中使用 Guzzle 包,它是一个用于发送 HTTP 请求的 PHP HTTP 客户端。
您可以通过 composer 安装 Guzzle
composer require guzzlehttp/guzzle:~6.0
或者您可以将 Guzzle 指定为项目现有 composer.json 中的依赖项
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
laravel 5 中使用 Guzzle 的示例代码如下所示,
use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
$client = new Client();
$res = $client->request('POST', 'https://url_to_the_api', [
'form_params' => [
'client_id' => 'test_id',
'secret' => 'test_secret',
]
]);
echo $res->getStatusCode();
// 200
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
}
// "200"
应该是 // 200
,因为返回的值是一个整数。
您只想调用外部 URL 并使用结果?如果我们谈论的是对服务 JSON 的东西的简单 GET 请求,PHP 开箱即用地做到了这一点:
$json = json_decode(file_get_contents('http://host.com/api/stuff/1'), true);
如果你想做一个发布请求,它会有点困难,但是有很多例子如何用 curl 做到这一点。
所以我想问题是;你到底想要什么?
从 Laravel v7.X 开始,该框架现在带有一个封装在 Guzzle HTTP client 周围的最小 API。它提供了一种简单的方法来制作 get、post、put、patch 和 delete strong> 使用 HTTP Client 的请求:
use Illuminate\Support\Facades\Http;
$response = Http::get('http://test.com');
$response = Http::post('http://test.com');
$response = Http::put('http://test.com');
$response = Http::patch('http://test.com');
$response = Http::delete('http://test.com');
您可以使用返回的 Illuminate\Http\Client\Response
实例提供的一组方法来管理响应。
$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
请注意,您当然需要像这样安装 Guzzle:
composer require guzzlehttp/guzzle
内置了更多有用的功能,您可以在此处找到有关这些功能集的更多信息:https://laravel.com/docs/7.x/http-client
这绝对是现在在 Laravel 中进行外部 API 调用的最简单方法。
更新于 2019 年 3 月 21 日
使用 composer require guzzlehttp/guzzle:~6.3.3
添加 GuzzleHttp
包
或者,您可以在项目的 composer.json
中将 Guzzle 指定为依赖项
{
"require": {
"guzzlehttp/guzzle": "~6.3.3"
}
}
在您调用 API 的类的顶部包含以下行
use GuzzleHttp\Client;
添加以下代码以发出请求
$client = new Client();
$res = $client->request('POST', 'http://www.exmple.com/mydetails', [
'form_params' => [
'name' => 'george',
]
]);
if ($res->getStatusCode() == 200) { // 200 OK
$response_data = $res->getBody()->getContents();
}
明确地说,对于任何 PHP 项目,您可能希望使用 GuzzleHTTP 来发送请求。 Guzzle 有非常好的文档,您可以查看 here。我只想说,您可能希望在 Laravel 项目的任何组件(例如特征)中集中使用 Guzzle 的 Client 类,而不是在 Laravel 的多个控制器和组件上创建 Client 实例(如许多文章和答复建议)。
我创建了一个您可以尝试使用的特征,它允许您从 Laravel 项目的任何组件发送请求,只需使用它并调用 makeRequest
。
namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
/**
* Send a request to any service
* @return string
*/
public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
{
$client = new Client([
'base_uri' => $this->baseUri,
]);
$bodyType = 'form_params';
if ($hasFile) {
$bodyType = 'multipart';
$multipart = [];
foreach ($formParams as $name => $contents) {
$multipart[] = [
'name' => $name,
'contents' => $contents
];
}
}
$response = $client->request($method, $requestUrl, [
'query' => $queryParams,
$bodyType => $hasFile ? $multipart : $formParams,
'headers' => $headers,
]);
$response = $response->getBody()->getContents();
return $response;
}
}
请注意,此 trait 甚至可以处理文件发送。
如果您想了解有关此 trait 的更多详细信息以及将此 trait 集成到 Laravel 的其他内容,请查看此 article。此外,如果对此主题感兴趣或需要重大帮助,您可以参加my course,它会在整个过程中为您提供指导。
希望对大家有所帮助。
最好的祝愿 :)
Laravel 8 的基本解决方案是
use Illuminate\Support\Facades\Http;
$response = Http::get('http://example.com');
“GuzzleHTTP 发送请求”和“Illuminate\Http\Request;”之间存在冲突不要问我为什么... [这里是可搜索的]
所以寻找我在 Laravel 8 Doc 中找到的 1sec ......
https://laravel.com/docs/8.x/http-client#making-requests
如你看到的
https://laravel.com/docs/8.x/http-client#introduction
Laravel 围绕 Guzzle HTTP 客户端提供了一个富有表现力的最小 API,允许您快速发出传出 HTTP 请求以与其他 Web 应用程序通信。 Laravel 围绕 Guzzle 的封装专注于其最常见的用例和出色的开发人员体验。
它对我很有用,玩得开心,如果有帮助,请指出!
您可以使用 Httpful :
GitHub:https://github.com/nategood/httpful
我还创建了类似于@JuanDMeGon 的特征,您可以在项目中的任何地方使用它。请检查一下
trait ApiRequests
{
public function get($url, $data = null)
{
try {
$response = Http::get($this->base_url . $url, $data);
} catch (\Exception $e) {
info($e->getMessage());
abort(503);
}
if ( $response->status() == 401) {
throw new AuthenticationException();
} else if (! $response->successful()) {
abort(503);
}
return $response->json();
}
public function post($url, $data = [])
{
$token = session()->get('token');
try {
$response = Http::acceptJson()->withToken($token)->post($this->base_url . $url, $data);
} catch (\Exception $e) {
abort(503);
}
if ($response->status() == 401 && !request()->routeIs('login')) {
throw new AuthenticationException();
}
return $response;
}
}
class Controller extends BaseController
{
protected $base_url;
use AuthorizesRequests, DispatchesJobs, ValidatesRequests, ApiRequests;
public function __construct()
{
$this->base_url = env("BASE_URL","http://192.168.xxxxxxx");
View::share('base_url', $this->base_url);
}
}
不定期副业成功案例分享