byjg/webrequest

一个轻量且高度定制的CURL包装器,用于发送RESt调用和动态SOAP请求的包装器。

4.9.2 2024-05-30 17:00 UTC

This package is auto-updated.

Last update: 2024-09-16 14:44:04 UTC


README

Opensource ByJG Build Status GitHub source GitHub license GitHub release

一个轻量级的PSR-7实现,以及一个用于发送RESt调用的定制化CURL包装器。

主要特性

此类实现了

  • PSR-7请求和响应;
  • PSR-18 Http客户端
  • 可通过部分实现PSR-18进行定制的HttpClient
  • 创建请求实例的辅助器,用于最常见的用例;
  • 并行执行多个请求的包装器;

PSR-7实现和基本用法

由于实现遵循PSR7实现,因此关于使用的解释并不多。

关键元素包括

  • URI - 将定义具有参数的URI,路径,主机,方案等;
  • 请求 - 将设置请求头和方法;
  • 响应 - 将接收响应头,主体和状态码。

有关PSR-7的更多信息,请参阅: https://www.php-fig.org/psr/psr-7/

发送请求对象的实现由HttpClient类定义。此类部分遵循PSR-18实现。因此,一旦定义了请求实例,只需调用HttpClient::sendRequest($request);

基本用法

<?php
$uri = \ByJG\Util\Uri::getInstanceFromString('http://www.example.com/page');
$request = \ByJG\Util\Psr7\Request::getInstance($uri);
$response = \ByJG\Util\HttpClient::getInstance()->sendRequest($request);

传递参数

<?php
$uri = \ByJG\Util\Uri::getInstanceFromString('http://www.example.com/page')
    ->withQuery(http_build_query(['param'=>'value']));

$request = \ByJG\Util\Psr7\Request::getInstance($uri);
$response = \ByJG\Util\HttpClient::getInstance()->sendRequest($request);

辅助类

WebRequest包具有辅助类,使其能够轻松为某些用例创建请求实例。

传递字符串有效负载(JSON)

<?php
$uri = \ByJG\Util\Uri::getInstanceFromString('http://www.example.com/page');
$request = \ByJG\Util\Helper\RequestJson::build(
   $uri,
   "POST",
   '{teste: "value"}'  // Support an associate array
);
$response = \ByJG\Util\HttpClient::getInstance()->sendRequest($request);

创建表单URL编码(模拟HTTP表单)

<?php
$uri = \ByJG\Util\Uri::getInstanceFromString('http://www.example.com/page');
$request = \ByJG\Util\Helper\RequestFormUrlEncoded::build(
   $uri,
   ["param" => "value"]
);
$response = \ByJG\Util\HttpClient::getInstance()->sendRequest($request);

创建多部分请求(上传文档)

<?php
$uri = \ByJG\Util\Uri::getInstanceFromString('http://www.example.com/page');

// Define the contents to upload using a list of MultiPartItem objects
$uploadFile = [];
$uploadFile[] = new \ByJG\Util\MultiPartItem('field1', 'value1');
$uploadFile[] = new \ByJG\Util\MultiPartItem(
    'field2',
    '{"key": "value2"}',
    'filename.json',
    'application/json; charset=UTF-8'
);
$uploadFile[] = new \ByJG\Util\MultiPartItem('field3', 'value3');

// Use the Wrapper to create the Request
$request = \ByJG\Util\Helper\RequestMultiPart::build(Uri::getInstanceFromString($uri),
    "POST",
    $uploadFile
);

// Do the request as usual
$response = \ByJG\Util\HttpClient::getInstance()->sendRequest($request);

自定义HttpClient

自定义选项包括

<?php

$client = \ByJG\Util\HttpClient::getInstance()
    ->withNoFollowRedirect()         // HttpClient will not follow redirects (status codes 301 and 302). Default is follow 
    ->withNoSSLVerification()        // HttpClient will not validate the SSL certificate. Default is validate.
    ->withProxy($uri)                // Define a http Proxy based on the URI. 
    ->withCurlOption($key, $value)   // Set an arbitrary CURL option (use with caution)
;

HttpClientParallel

您可以使用HttpClient并行执行多个不同的请求。

要使用此功能,您需要

  1. 创建HttpClientParallel类的实例
  2. 添加RequestInterface实例
  3. 执行

结果将一准备好就处理。

以下是一个基本示例

<?php
// Create the instances of the requirements
$httpClient = \ByJG\Util\HttpClient::getInstance();

$onSucess = function ($response, $id) {
    // Do something with Response object
};

$onError = function ($error, $id) use (&$fail) {
    // Do something
};

// Create the HttpClientParallel
$multi = new \ByJG\Util\HttpClientParallel(
    $httpClient,
    $onSucess,
    $onError
);

// Add the request to run in parallel
$request1 = Request::getInstance($uri1);
$request2 = Request::getInstance($uri2);
$request3 = Request::getInstance($uri3);

$multi
    ->addRequest($request1)
    ->addRequest($request2)
    ->addRequest($request3);

// Start execute and wait to finish
// The results will be get from the closure defined above. 
$multi->execute();

模拟HttpClient

MockClient类具有与HttpClient相同的所有方法,除了

  • 不会向服务器发送任何请求;
  • 您可以添加预期的响应对象;
  • 您可以在提交请求后收集CURL的信息。

设置预期的响应对象

<?php
$expectedResponse = new Response(200);

$mock = $this->object = new MockClient($expectedResponse);
$response = $mock->sendRequest(new Request("http://example.com"));

assertEquals($expectedResponse, $response);

调试CURL选项

<?php
$expectedResponse = new Response(200);

$mock = $this->object = new MockClient($expectedResponse);
$response = $mock->sendRequest(new Request("http://example.com"));

$expectedCurlOptions = [
    CURLOPT_CONNECTTIMEOUT => 30,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HEADER => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)",
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_SSL_VERIFYPEER => 1,
    CURLOPT_HTTPHEADER => [
        'Host: localhost:8080'
    ],
];

assertEquals($expectedCurlOptions, $mock->getCurlConfiguration());

MockClient中的其他方法

以下方法在sendRequest()方法执行后可用

  • getCurlConfiguration()
  • getRequestedObject()
  • getExpectedResponse()

安装

composer install "byjg/webrequest"

运行测试

启动服务器

我们提供了docker-compose,以便可以轻松启动测试服务器。

docker-compose up -d 

运行集成测试

vendor/bin/phpunit

停止服务器

docker-compose down

依赖项

开源ByJG