Http 类提供用于通过 HTTP 协议打开连接的功能。 你可以使用它来建立到其他应用程序和服务的出站连接。 该客户端由 Laravel 框架提供,你可以在 Laravel 文档文章 中了解所有可能的功能。
要发送请求,PHP 方法将与 HTTP 方法关联,它支持 get、post、patch、put、options 和 delete。 以下是一个基本的 GET URL 请求示例。 返回结果将包含一个响应对象。
$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);