andrey-tech/http-client-php

简单的 PHP7+ HTTP(S) 客户端,具有请求节流和 JSON 格式消息体中 BOM 标记的支持

3.0.7 2024-01-15 17:33 UTC

This package is auto-updated.

Last update: 2024-09-15 19:01:18 UTC


README

简单的 PHP7+ HTTP(S) 客户端,具有请求节流、支持 JSON 格式消息体的 BOM 标记和将请求和响应的调试信息输出到 STDOUT

Latest Stable Version Total Downloads License

内容

要求

  • PHP >= 7.0;
  • 任意遵循 PSR-4 标准的类自动加载器。

安装

通过 composer 安装

$ composer require andrey-tech/http-client-php:"^3.0"

或添加

"andrey-tech/http-client-php": "^3.0"

到 composer.json 文件的 require 部分。

HTTP

\App\HTTP\HTTP 确保

  • 执行 HTTP(S) 协议请求;
  • 可配置的请求节流;
  • 检查服务器 SSL/TLS 证书,并可选择禁用;
  • 在 JSON 格式的消息体中添加或删除 BOM 标记;
  • 将请求和响应的调试信息输出到 STDOUT。

在出现错误时抛出 \App\HTTP\HTTPException 类的异常。

类方法

  • __construct() 类构造函数。
  • request(string $url, string $method = 'GET', array $params = [], array $requestHeaders = [], array $curlOptions = []) :?array
    发送 HTTP(S) 请求。返回服务器的解码响应或 cURL 错误时的 null。
    • $url - 请求的 URL;
    • $method - 请求方法;
    • $params - 请求参数;
    • $curlOptions - cURL 的额外参数。
  • isSuccess(array $successStatusCodes = []) :bool 返回请求执行的成功状态。
    • $successStatisCodes 成功执行的 HTTP 状态码。如果没有提供,则使用默认值,该默认值在 $successStatusCodes 属性中设置。
  • getHTTPCode() :int 返回最后一次请求的 HTTP 状态码。
  • getResponse() :?string 返回最后一次响应的原始体。
  • getResponseHeaders() :array 返回最后一次响应的头部信息。
  • getCurlInfo() :array 返回最后一次 cURL 操作的信息。

参数

额外的参数通过类 \App\HTTP\HTTP 的公共属性设置。

示例

use App\HTTP\HTTP;
use App\HTTP\HTTPException;

try {
    // Создаем клиента
    $http = new HTTP();

    // Устанавливаем максимальный уровень вывода отладочных сообщений в STDOUT
    $http->debugLevel = HTTP::DEBUG_URL |  HTTP::DEBUG_HEADERS | HTTP::DEBUG_CONTENT;

    // Устанавливаем троттлинг запросов на уровне не более 1 запроса в 2 секунды
    $http->throttle = 0.5;

    // Устанавливаем таймаут соединения в 30 секунд
    $http->curlConnectTimeout = 30;

    // Устанавливаем таймаут обмена данными в 30 секунд
    $http->curlTimeout = 30;

    // Отправляем POST запрос
    $response = $http->request(
        $url            = 'https://www.example.com',
        $method         = 'POST',
        $params         = [ 'username' => 'ivan@example.com', 'password' => '1234567890' ],
        $requestHeaders = [ 'Content-Type: application/json' ]
    );

    // Проверяем НТТР статус ответа
    if (! $http->isSuccess()) {
        $httpCode = $http->getHTTPCode();
        $response = $http->getResponse();
        throw new HTTPException("HTTP {$httpCode}: {$response}");
    }

    print_r($response);

} catch (HTTPException $e) {
    printf('Ошибка (%d): %s' . PHP_EOL, $e->getCode(), $e->getMessage());
}

调试消息示例

[1] ===> POST https://www.example.com
POST / HTTP/1.1
Host: www.example.com
User-Agent: HTTP-client/3.x.x
Accept: */*
Content-Type: application/json
Content-Length: 55

{"username":"ivan@example.com","password":"1234567890"}

[1] <=== RESPONSE 0.9269s (200)
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Sun, 14 Jun 2020 13:09:33 GMT
Etag: "3147526947"
Expires: Sun, 21 Jun 2020 13:09:33 GMT
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
Server: EOS (vny/0453)
Content-Length: 1256

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
</head>
<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

作者

© 2019-2022 andrey-tech

许可证

本库在 MIT 许可证下分发。