arturdoruch / http
发送HTTP请求的HTTP客户端。
Requires
- php: >=5.4
- symfony/event-dispatcher: >=2.6 <6.0
This package is auto-updated.
Last update: 2024-09-12 09:01:41 UTC
README
发送HTTP请求的HTTP客户端。
安装
composer require "arturdoruch/http"
用法
基本用法
use ArturDoruch\Http\Client; $client = new Client(); // Send GET request. $response = $client->get('http://httpbin.org/get'); // Get response status code. $statusCode = $response->getStatusCode(); // Get response body. $body = $response->getBody(); // Display response raw headers and body. echo $response; // Display response headers. foreach ($response->getHeaders() as $name => $value) { echo sprintf("%s: %s\n", $name, $value); }
创建客户端
use ArturDoruch\Http\Cookie\CookieFile; use ArturDoruch\Http\Client; // Set the cURL options, which will be used for send every HTTP request. $curlOptions = [ 'followlocation' => false, 'timeout' => 120 ]; // Enabled or disabled throwing RequestException, when request is complete and response status code is 4xx, 5xx or 0. $throwExceptions = true; // Set file where all HTTP session cookies should be stored. $cookieFile = new CookieFile('path/to/cookies.txt'); $client = new Client($curlOptions, $throwExceptions, $cookieFile);
发送请求
请求可以通过专用方法发送
$response = $client->get('http://httpbin.org/get'); $response = $client->post('http://httpbin.org/post'); $response = $client->patch('http://httpbin.org/patch'); $response = $client->put('http://httpbin.org/put'); $response = $client->delete('http://httpbin.org/delete');
或通过 request()
方法,使用已准备好的 ArturDoruch\Http\Request
对象。
use ArturDoruch\Http\Request; $request = new Request('DELETE', 'http://httpbin.org/delete'); $response = $client->request($request);
发送多(并行)请求
$requests = [ // The list of ArturDoruch\Http\Request objects or URLs to send. ]; $responses = $client->multiRequest($requests); foreach ($responses as $response) { var_dump($response->getBody()); }
发送表单数据(参数)
$formData = [ 'name' => 'value', 'choices' => [1, 2, 3] ]; $response = $client->post('http://httpbin.org/post', $formData); $request = new Request('POST', 'http://httpbin.org/post', $formData); $response = $client->request($request);
表单数据只能通过以下请求方法发送: POST
、PUT
、PATCH
和 DELETE
。对于其他方法,表单数据将用作URL查询参数。
请求选项
请求选项可以通过 ArturDoruch\Http\Request
对象上的专用方法设置,或在 Client::get()
、Client::post()
等方法中作为第三个参数,或在 Client::createRequest()
方法中作为第四个参数。
-
cookie
字符串设置要发送的cookie。cookie格式必须符合规范。
$client->get('/get', [], [ 'cookie' => 'NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure' ]);
-
headers
数组$client->get('/get', [], [ 'headers' => [ 'User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'] ] ]);
-
body
字符串|资源设置正文纯文本。如果未指定
Content-Type
头,则将其设置为text/plain
。// Send body as plain text taken from a resource. $resource = fopen('http://httpbin.org', 'r'); $client->post('/post', [], ['body' => $resource]); // Send plain text. $client->post('/post', [], ['body' => 'Raw data']);
-
json
数组将正文设置为JSON数据。如果未指定
Content-Type
头,则将其设置为application/json
。$client->post('/post', [], [ 'json' => [ 'foo' => 'bar', 'key' => 'value' ] ]);
-
multipart
数组将正文设置为多部分表单数据。对于发送文件,创建
ArturDoruch\Http\Message\FormFile
对象并将其作为表单字段值传递。如果未指定Content-Type
头,则将其设置为multipart/form-data; boundary=
。use ArturDoruch\Http\Message\FormFile; $client->post('/post', [], [ 'multipart' => [ 'name' => 'value', 'categories' => [ 'animals' => ['dog', 'cat'], ], 'file' => new FormFile('/path/file.txt.', 'optional-custom-filename.txt') ] ]);
HTTP请求事件
在发送HTTP请求期间,会调用两个事件
request.before
- 在发送请求之前调用。request.complete
- 在请求完成时调用。
要为这些事件添加监听器,请调用 Client::addListener()
方法。已注册的监听器根据要监听的事件接收参数。其中一个是
ArturDoruch\Http\Event\BeforeEvent
- 用于request.before
事件ArturDoruch\Http\Event\CompleteEvent
- 用于request.complete
事件
use App\EventListener\HttpRequestListener; use ArturDoruch\Http\Event\BeforeEvent; use ArturDoruch\Http\Event\CompleteEvent; use ArturDoruch\Http\Event\RequestEvents; // Add listener to request.before event as anonymous function. $client->addListener(RequestEvents::BEFORE, function (BeforeEvent $event) { $request = $event->getRequest(); }); // Add listener to request.before event as method class. $client->addListener(RequestEvents::BEFORE, [new HttpRequestListener(), 'onBefore']); // Add listener to request.complete event as method class. $client->addListener(RequestEvents::COMPLETE, [new HttpRequestListener(), 'onComplete']);
HttpRequestListener
类的示例。
namespace App\EventListener; use ArturDoruch\Http\Event\BeforeEvent; use ArturDoruch\Http\Event\CompleteEvent; class HttpRequestListener { /** * @param BeforeEvent $event */ public function onBefore(BeforeEvent $event) { $request = $event->getRequest(); // Do some actions before HTTP request is sending. } /** * @param CompleteEvent $event */ public function onComplete(CompleteEvent $event) { $response = $event->getResponse(); // Do some actions when HTTP request is complete. } }
将响应对象转换为数组或json
要将响应对象转换为数组,请调用 Response::toArray() 方法。
$responseArray = $response->toArray();
要将响应对象转换为json,请调用 Response::toJson() 方法。
$responseJson = $response->toJson(); // Use JSON_PRETTY_PRINT option to format output json $responseJson = $response->toJson(true);
要确定在转换后的输出值中应使用哪些响应对象属性,请使用 Response::expose() 方法。此方法接受一个名为 "properties" 的参数,其中包含要公开的属性名称列表。可用名称包括
- 协议
- statusCode
- reasonPhrase
- headers
- headerLines
- body
- contentType
- requestUrl
- effectiveUrl
- errorMsg
- errorNumber
- curlInfo
默认情况下,公开的属性是:statusCode、headers、body。
// Expose only the "statusCode" and "body" properties. $response->expose([ 'statusCode', 'body', ]); // The array will contain only "statusCode" and "body" keys. $responseArray = $response->toArray();
要公开所有响应属性,请使用 exposeAll() 方法。
// Expose all properties. $response->exposeAll(); // The array will contain all of available properties. $responseArray = $response->toArray();
提示
- 获取实际发送的请求头。
$client = new Client([CURLINFO_HEADER_OUT => true]); $response = $client->get('http://httpbin.org/get'); $curlInfo = $response->getCurlInfo() $requestHeaders = $curlInfo['request_header'];