chillerlan/php-httpinterface

PSR-7/17/18 HTTP 消息/客户端实现

6.0.0 2024-03-15 22:17 UTC

This package is auto-updated.

Last update: 2024-09-15 23:44:14 UTC


README

PSR-7/PSR-17/PSR-18 HTTP 消息/客户端实现。

PHP Version Support version license Continuous Integration Coverage Codacy Packagist downloads

文档

使用 phpDocumentor 创建的 API 文档可以在 https://chillerlan.github.io/php-httpinterface/ 找到(工作进度中)。

需求

使用 composer 安装

终端

composer require chillerlan/php-httpinterface

composer.json

{
	"require": {
		"php": "^8.1",
		"chillerlan/php-httpinterface": "dev-main#<commit_hash>"
	}
}

注意:将 dev-main 替换为 版本约束,例如 ^6.0 - 请参阅 版本发布 以获取有效版本。

成功了!

快速入门

HTTP 客户端 CurlClientStreamClient 使用 ResponseFactoryInterface 实例作为第一个参数调用,然后是可选的 HTTPOptions 和 PSR-3 LoggerInterface 实例。然后,您可以通过实现的 PSR-18 方法 ClientInterface::sendRequest(),使用 PSR-7 RequestInterface 发送请求,并期望得到一个 PSR-7 ResponseInterface

CurlClientStreamClient

$options                 = new HTTPOptions;
$options->ca_info        = '/path/to/cacert.pem';
$options->user_agent     = 'my cool user agent 1.0';
$options->dns_over_https = 'https://cloudflare-dns.com/dns-query';

$httpClient = new CurlClient($responseFactory, $options, $logger);
$request    = $requestFactory->createRequest('GET', 'https://www.example.com?foo=bar');

$httpClient->sendRequest($request);

CurlMultiClient

CurlMultiClient 客户端实现了异步多请求("rolling-curl")。它需要一个 MultiResponseHandlerInterface 来解析传入的响应,回调可以返回一个失败请求到堆栈

$handler = new class () implements MultiResponseHandlerInterface{

	public function handleResponse(
		ResponseInterface $response,  // the incoming response
		RequestInterface  $request,   // the corresponding request
		int               $id,        // the request id
		array|null        $curl_info, // the curl_getinfo() result for this request
	):RequestInterface|null{
	
		if($response->getStatusCode() !== 200){
			// return the failed request back to the stack
			return $request;
		}
		
		try{
			$body = $response->getBody();
			
			// the response body is empty for some reason, we pretend that's fine and exit
			if($body->getSize() === 0){
				return null;
			}
			
			// parse the response body, store the result etc.
			$data = $body->getContents();
			
			// save data to file, database or whatever...
			// ...
	
		}
		catch(Throwable){
			// something went wrong, return the request to the stack for another try
			return $request;
		}
		
		// everything ok, nothing to return
		return null;
	}

};

然后可以调用多请求客户端 - MultiResponseHandlerInterfaceResponseFactoryInterface 是必需的,HTTPOptionsLoggerInterface 是可选的

$options              = new HTTPOptions;
$options->ca_info     = '/path/to/cacert.pem';
$options->user_agent  = 'my cool user agent 1.0';
$options->sleep       = 750000; // microseconds, see usleep()
$options->window_size = 5;
$options->retries     = 1;

$multiClient = new CurlMultiClient($handler, $responseFactory, $options, $logger);

// create and add the requests
foreach(['..', '...', '....'] as $item){
	$multiClient->addRequest($factory->createRequest('GET', $endpoint.'/'.$item));
}

// process the queue
$multiClient->process();

URLExtractor

URLExtractor 包装了一个 PSR-18 ClientInterface,以提取和跟踪缩短的 URL 到它们的原始位置。

$options                 = new HTTPOptions;
$options->user_agent     = 'my cool user agent 1.0';
$options->ssl_verifypeer = false;
$options->curl_options   = [
	CURLOPT_FOLLOWLOCATION => false,
	CURLOPT_MAXREDIRS      => 25,
];

$httpClient   = new CurlClient($responseFactory, $options, $logger);
$urlExtractor = new URLExtractor($httpClient, $responseFactory);

$request = $factory->createRequest('GET', 'https://t.co/ZSS6nVOcVp');

$urlExtractor->sendRequest($request); // -> response from the final location

// you can retrieve an array with all followed locations afterwards
$responses = $this->http->getResponses(); // -> ResponseInterface[]

// if you just want the URL of the final location, you can use the extract method: 
$url = $this->http->extract('https://t.co/ZSS6nVOcVp'); // -> https://api.guildwars2.com/v2/build

LoggingClient

LoggingClient 包装了一个 ClientInterface,并通过一个 LoggerInterface 以可读的方式输出 HTTP 消息(不要在生产环境中使用!)。

$loggingClient = new LoggingClient($httpClient, $logger);

$loggingClient->sendRequest($request); // -> log to output given via logger

自动生成的 API 文档

API 文档可以使用 phpDocumentor 自动生成。有一个通过 gh-pages 分支 可用的在线版本,它会在向主分支推送时自动部署。

本地创建的文档将出现在 .build/phpdocs/ 目录中。如果您想创建本地文档,请按照以下步骤操作

  • 下载 phpDocumentor v3+ 作为 .phar 归档
  • 在存储库根目录中运行它
    • 在 Windows 上 c:\path\to\php.exe c:\path\to\phpDocumentor.phar --config=phpdoc.xml
    • 在 Linux 上只是 php /path/to/phpDocumentor.phar --config=phpdoc.xml
  • 在浏览器中打开 index.html
  • 盈利!

免责声明

风险自负!