Http 类提供了通过 HTTP 协议打开连接的功能。你可以使用它来与其他的应用程序和服务建立对外连接。此客户端由 Laravel 框架提供,你可以在 Laravel 文档文章 中了解所有可能的功能。
要发起请求,PHP 方法将关联到 HTTP 方法,它支持 get、post、patch、put、options 和 delete. 以下是一个向 URL 发送基本 GET 请求的示例. 返回的结果将包含一个响应对象.
$response = Http::get('https://octobercms.com');你可以通过在方法调用前加上 dd() 来快速轻松地检查请求的内容。这将转储请求的内容并终止执行。
Http::dd()->get('https://octobercms.com');响应对象将提供可用于检查响应的方法。
$result = Http::post('https://octobercms.com');
echo $result->body(); // Outputs: <html><head><title>...
echo $result->status(); // Outputs: 200
echo $result->header('Content-Type'); // Outputs: text/html; charset=UTF-8该对象支持以下方法调用。
| Method Name | Return Type | Purpose | |
|---|---|---|---|
| body() | string | Get the body of the response. | |
| json($key) | `array | mixed` | Get the JSON decoded body of the response as an array or scalar value. |
| object() | object | Get the JSON decoded body of the response as an object. | |
| collect($key) | Collection | Get the JSON decoded body of the response as a collection. | |
| status() | int | Get the status code of the response. | |
| ok() | bool | Determine if the response code was "OK". | |
| successful() | bool | Determine if the request was successful. | |
| redirect() | bool | Determine if the response was a redirect. | |
| failed() | bool | Determine if the response indicates a client or server error occurred. | |
| serverError() | bool | Determine if the response indicates a server error occurred. | |
| clientError() | bool | Determine if the response indicates a client error occurred. | |
| header($header) | string | Get a header from the response. | |
| headers() | array | Get the headers from the response. |
post、put 和 patch 方法支持在请求中发送额外数据。默认情况下,数据使用 application/json 作为内容类型发送。
Http::post('https://octobercms.com', [
'name' => 'Jeff'
]);要改用 application/x-www-form-urlencoded 内容类型发送数据,请在发出请求之前调用 asForm 方法。
Http::asForm()->post('https://octobercms.com', [
'name' => 'Jeff'
]);在使用 get 请求时传递数据,该数组将随查询字符串一起包含在 URL 中。
Http::get('https://octobercms.com', [
'page' => '1'
]);withHeaders 方法可用于在请求中包含自定义请求头。
Http::withHeaders([
'Rest-Key' => '...'
])->post('https://octobercms.com', [
'name' => 'Jeff'
]);该 withBasicAuth 方法用于随请求传递认证凭据。
Http::withBasicAuth('user', 'password')->post('https://octobercms.com', [
'name' => 'Jeff'
]);HTTP 客户端将所有响应视为有效, 包括错误, 因此要确定是否发生了错误,您应该检查 successful, failed, clientError, 或 serverError 方法.
// Status code is >= 200 and < 300
$response->successful();
// Status code is >= 400
$response->failed();
// Response has a 400 level status code
$response->clientError();
// Response has a 500 level status code
$response->serverError();您还可以使用 onError 方法在发生客户端或服务器错误时执行回调。
$response->onError(callable $callback);