php 从 Laravel 向外部 API 发出 HTTP 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22355828/
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
Doing HTTP requests FROM Laravel to an external API
提问by Chilion
What I want is get an object from an API with a HTTP (eg, jQuery's AJAX) request to an external api. How do I start? I did research on Mr Google but I can't find anything helping.
我想要的是从一个带有 HTTP(例如,jQuery 的 AJAX)请求的 API 获取一个对象到一个外部 api。我该如何开始?我对谷歌先生进行了研究,但找不到任何帮助。
Im starting to wonder is this is even possible? In this post Laravel 4 make post request from controller to external url with datait looks like it can be done. But there's no example nor any source where to find some documentation.
我开始怀疑这可能吗?在这篇文章中,Laravel 4 使用数据从控制器向外部 url 发出 post 请求,看起来可以完成。但是没有示例或任何来源可以找到一些文档。
Please help me out?
请帮帮我?
回答by AI Snoek
Based upon an answer of a similar question here: https://stackoverflow.com/a/22695523/1412268
基于这里类似问题的答案:https: //stackoverflow.com/a/22695523/1412268
Take a look at Guzzle
看看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", ....
回答by Mohammed Safeer
We can use package Guzzle in Laravel, it is a PHP HTTP client to send HTTP requests.
我们可以在 Laravel 中使用 Guzzle 包,它是一个发送 HTTP 请求的 PHP HTTP 客户端。
You can install Guzzle through composer
你可以通过 composer 安装 Guzzle
composer require guzzlehttp/guzzle:~6.0
Or you can specify Guzzle as a dependency in your project's existing composer.json
或者您可以在项目现有的 composer.json 中将 Guzzle 指定为依赖项
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
Example code in laravel 5 using Guzzle as shown below,
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"...'
}
回答by Bram
You just want to call an external URL and use the results? PHP does this out of the box, if we're talking about a simple GET request to something serving JSON:
您只想调用外部 URL 并使用结果?PHP 开箱即用,如果我们谈论的是一个对 JSON 服务的简单 GET 请求:
$json = json_decode(file_get_contents('http://host.com/api/stuff/1'), true);
If you want to do a post request, it's a little harder but there's loads of examples how to do this with curl.
如果你想做一个 post 请求,它有点难,但是有很多例子如何使用 curl 来做到这一点。
So I guess the question is; what exactly do you want?
所以我想问题是;你到底想要什么?
回答by mujuonly
Updated on March 21 2019
2019 年 3 月 21 日更新
Add GuzzleHttppackage using composer require guzzlehttp/guzzle:~6.3.3
添加GuzzleHttp包使用composer require guzzlehttp/guzzle:~6.3.3
Or you can specify Guzzle as a dependency in your project's composer.json
或者您可以在项目的依赖项中指定 Guzzle composer.json
{
"require": {
"guzzlehttp/guzzle": "~6.3.3"
}
}
Include below line in the top of the class where you are calling the API
在您调用 API 的类的顶部包含以下行
use GuzzleHttp\Client;
Add below code for making the request
添加以下代码以发出请求
$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();
}
回答by JuanDMeGon
Definitively, for any PHP project, you may want to use GuzzleHTTP for sending requests. Guzzle has very nice documentation you can check here. I just want to say that, you probably want to centralize the usage of the Client class of Guzzle in any component of your Laravel project (for example a trait) instead of being creating Client instances on several controllers and components of Laravel (as many articles and replies suggest).
毫无疑问,对于任何 PHP 项目,您可能希望使用 GuzzleHTTP 发送请求。Guzzle 有非常好的文档,您可以在此处查看。我只想说,您可能希望在 Laravel 项目的任何组件(例如 trait)中集中使用 Guzzle 的 Client 类,而不是在 Laravel 的多个控制器和组件上创建 Client 实例(如许多文章和回复建议)。
I created a trait you can try to use, which allows you to send requests from any component of your Laravel project, just using it and calling to makeRequest.
我创建了一个你可以尝试使用的特性,它允许你从 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;
}
}
Notice this trait can even handle files sending.
请注意,此 trait 甚至可以处理文件发送。
If you want more details about this trait and some other stuff to integrate this trait to Laravel, check this article. Additionally, if interested in this topic or need major assistance, you can take my coursewhich guides you in the whole process.
如果您想了解有关此 trait 的更多详细信息以及其他一些将此 trait 集成到 Laravel 的内容,请查看这篇文章。此外,如果对此主题感兴趣或需要重大帮助,您可以参加我的课程,该课程将指导您完成整个过程。
I hope it helps all of you.
我希望它对你们所有人都有帮助。
Best wishes :)
最好的祝愿 :)
回答by Syclone
As of Laravel v7.X, the framework now comes with a minimal API wrapped around the Guzzle HTTP client. It provides an easy way to make get, post, put, patch, and deleterequests using the HTTP Client:
从Laravel v7.X 开始,该框架现在带有一个围绕Guzzle HTTP 客户端包装的最小 API 。它提供了一种使用HTTP 客户端发出get、post、put、patch和delete请求的简单方法:
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');
You can manage responses using the set of methods provided by the Illuminate\Http\Client\Responseinstance returned.
您可以使用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;
Please note that you will, of course, need to install Guzzle like so:
请注意,您当然需要像这样安装 Guzzle:
composer require guzzlehttp/guzzle
There are a lot more helpful features built-in and you can find out more about these set of the feature here: https://laravel.com/docs/7.x/http-client
内置了更多有用的功能,您可以在此处找到有关这些功能集的更多信息:https: //laravel.com/docs/7.x/http-client
This is definitely now the easiest way to make external API calls within Laravel.
这绝对是现在在 Laravel 中进行外部 API 调用的最简单方法。
回答by Jeremie Ges
You can use Httpful :
您可以使用 Httpful :
Website : http://phphttpclient.com/
Github : https://github.com/nategood/httpful
Github:https: //github.com/nategood/httpful

