lumax/http-component

处理 HTTP 请求/响应的组件

2.3.0 2024-07-18 04:55 UTC

This package is auto-updated.

Last update: 2024-09-18 05:19:04 UTC


README

Version 2.3.0 PHP Coverage 79.23% License GPL--3.0--or--later

HTTP 组件是一个 PHP 库,旨在简化在应用程序中制作 HTTP 请求和处理 HTTP 响应的过程。它遵循 PSR-7 HTTP 消息接口 标准,使得它与遵循这些标准的其他库和框架兼容。

安装

您可以使用 Composer 安装此库

composer require lumax/http-component

功能

此 HTTP 组件包提供了以下关键特性

请求和响应处理

  • RequestResponse 类分别实现了 Psr\Http\Message\RequestInterfacePsr\Http\Message\ResponseInterface
  • 轻松创建和操作 HTTP 请求和响应。
  • 处理头部、请求方法、状态码等。

流处理

  • 一个 Stream 类,它实现了 Psr\Http\Message\StreamInterface,用于处理流数据。
  • 读取和写入流数据,检查流可用性等。

HTTP 客户端

  • 一个 HttpClient 类,它实现了 Psr\Http\Client\ClientInterface
  • 使用 cURL 发送 HTTP 请求并处理 HTTP 响应。
  • 支持常见的 HTTP 方法,如 GET、POST、PUT、PATCH 和 DELETE。
  • 自动解析响应头并处理重定向。

URI 处理

  • 一个 Uri 类,它实现了 Psr\Http\Message\UriInterface,用于处理 URI。
  • 轻松构建和操作 URI,包括处理方案、主机、端口、路径、查询和片段。

用法

创建 HTTP 请求

use Luma\HttpComponent\HttpClient;
use Luma\HttpComponent\Request;
use Luma\HttpComponent\StreamBuilder;
use Luma\HttpComponent\Uri;

// Create a URI
$uri = new Uri('https', 'example.com', '/');

// Create an HTTP GET request
$body = 'Some text!';
$request = new Request(
    'GET', 
    $uri, 
    ['Content-Type' => 'application/json'], 
    StreamBuilder::build($body)
);

// Customise the request headers
$request = $request->withHeader('Authorization', 'Bearer AccessToken');

// Send the request using the built-in HTTP Client
$response = (new HttpClient())->sendRequest($request);

// Get the response status code
$status = $response->getStatusCode();

// Get the response body
$body = $response->getBody()->getContents();

创建 HTTP 客户端

use Luma\HttpComponent\HttpClient;

// Create an HTTP client
$client = new HttpClient();

// Send GET request
$response = $client->get('https://example.com/api/resource');

// Send POST request to endpoint with headers and body
$response = $client->post(
    'https://example.com/api/resource', 
    ['Content-Type' => 'application/json', 'Authorization' => 'Bearer AccessToken'], 
    json_encode(['data' => 'value'])
);

处理流

use Luma\HttpComponent\StreamBuilder;

// Create a stream from a string
$stream = StreamBuilder::build('Hello, World!');

// Read from the stream
$data = $stream->read(1024);

// Write to the stream
$stream->write('New data to append');

// Rewind the streams internal pointer
$stream->rewind();

// Get the stream contents
$contents = $stream->getContents();

URI 处理

use Luma\HttpComponent\Uri;
use Luma\HttpComponent\Web\WebServerUri;

// Create a URI
$uri = new Uri('https', 'example.com', '/api/resource');

// Modify the URI
$uri = $uri->withScheme('http');
$uri = $uri->withPort(8888);
$uri = $uri->withQuery('new_param=new_value');

// Get the URI as a string
$uriString = $uri->__toString();

// Build a URI based on the current request to your web server
$uri = WebServerUri::generate();

许可证

此软件包是开源软件,根据 GNU 通用公共许可证第 3 版 (GPL-3.0) 许可。