workerman/http-client
Description
workerman/http-client is an asynchronous HTTP client component. All request responses are asynchronous and non-blocking, with a built-in connection pool, and the message requests and responses conform to the PSR7 specification.
Installation:
composer require workerman/http-client
Example:
Usage of get and post request
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker();
$worker->onWorkerStart = function () {
$http = new Workerman\Http\Client();
$http->get('https://example.com/', function ($response) {
var_dump($response->getStatusCode());
echo $response->getBody();
}, function ($exception) {
echo $exception;
});
$http->post('https://example.com/', ['key1' => 'value1', 'key2' => 'value2'], function ($response) {
var_dump($response->getStatusCode());
echo $response->getBody();
}, function ($exception) {
echo $exception;
});
$http->request('https://example.com/', [
'method' => 'POST',
'version' => '1.1',
'headers' => ['Connection' => 'keep-alive'],
'data' => ['key1' => 'value1', 'key2' => 'value2'],
'success' => function ($response) {
echo $response->getBody();
},
'error' => function ($exception) {
echo $exception;
}
]);
};
Worker::runAll();
File Upload
<?php
use Workerman\Worker;
require_once 'vendor/autoload.php';
$worker = new Worker();
$worker->onWorkerStart = function () {
$http = new Workerman\Http\Client();
// Upload file
$multipart = new \Workerman\Psr7\MultipartStream([
[
'name' => 'file',
'contents' => fopen(__FILE__, 'r')
],
[
'name' => 'json',
'contents' => json_encode(['a'=>1, 'b'=>2])
]
]);
$boundary = $multipart->getBoundary();
$http->request('http://127.0.0.1:8787', [
'method' => 'POST',
'version' => '1.1',
'headers' => ['Connection' => 'keep-alive', 'Content-Type' => "multipart/form-data; boundary=$boundary"],
'data' => $multipart,
'success' => function ($response) {
echo $response->getBody();
},
'error' => function ($exception) {
echo $exception;
}
]);
};
Worker::runAll();
Progress Streaming Response
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Connection\TcpConnection;
use Workerman\Http\Client;
use Workerman\Protocols\Http\Chunk;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
use Workerman\Worker;
$worker = new Worker('http://0.0.0.0:1234');
$worker->onMessage = function (TcpConnection $connection, Request $request) {
$http = new Client();
$http->request('https://api.ai.com/v1/chat/completions', [
'method' => 'POST',
'data' => json_encode([
'model' => 'gpt-3.5-turbo',
'temperature' => 1,
'stream' => true,
'messages' => [['role' => 'user', 'content' => 'hello']],
]),
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer sk-xxx',
],
'progress' => function($buffer) use ($connection) {
$connection->send(new Chunk($buffer));
},
'success' => function($response) use ($connection) {
$connection->send(new Chunk('')); // Sending an empty chunk denotes the end of the response
},
]);
$connection->send(new Response(200, [
//"Content-Type" => "application/octet-stream",
"Transfer-Encoding" => "chunked",
], ''));
};
Worker::runAll();
Options
<?php
require __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
$worker = new Worker();
$worker->onWorkerStart = function(){
$options = [
'max_conn_per_addr' => 128, // Max concurrent connections per domain
'keepalive_timeout' => 15, // How long to keep the connection open without communication
'connect_timeout' => 30, // Connection timeout duration
'timeout' => 30, // Timeout duration for waiting for a response after a request is sent
];
$http = new Workerman\Http\Client($options);
$http->get('http://example.com/', function($response){
var_dump($response->getStatusCode());
echo $response->getBody();
}, function($exception){
echo $exception;
});
};
Worker::runAll();
Coroutine Usage
Note
Coroutine usage requires workerman>=5.1, http-client>=3.0, and the installation of theswooleorswowextension, or usecomposer require revolt/event-loopto support Fiber driver.
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker();
$worker->eventLoop = \Workerman\Events\Swoole::class; // Or \Workerman\Events\Swow::class or \Workerman\Events\Fiber::class
$worker->onWorkerStart = function () {
$http = new Workerman\Http\Client();
$response = $http->get('https://example.com/');
var_dump($response->getStatusCode());
echo $response->getBody();
$response = $http->post('https://example.com/', ['key1' => 'value1', 'key2' => 'value2']);
var_dump($response->getStatusCode());
echo $response->getBody();
$response = $http->request('https://example.com/', [
'method' => 'POST',
'version' => '1.1',
'headers' => ['Connection' => 'keep-alive'],
'data' => ['key1' => 'value1', 'key2' => 'value2'],
]);
echo $response->getBody();
};
Worker::runAll();
When no callback function is set, the client returns the result of the asynchronous request in a synchronous manner, meaning that the request process does not block the current process, allowing concurrent request handling.
Note:
-
The project must first load
require __DIR__ . '/vendor/autoload.php'; -
All asynchronous code can only run in the environment after the workerman starts.
-
Supports all projects developed based on workerman, including Webman, GatewayWorker, PHPSocket.io, etc.
-
Try to preserve the client object for reuse, which can fully utilize the connection pool to improve performance, instead of creating a new object with
new Workerman\Http\Client()each time.
Usage in Webman
If you need to use asynchronous HTTP requests in webman and return the results to the frontend, refer to the following usage.
<?php
namespace app\controller;
use support\Request;
use support\Response;
use Workerman\Protocols\Http\Chunk;
class IndexController
{
public function index(Request $request)
{
// Preserve the client object for reuse, which can significantly improve performance
static $http;
$connection = $request->connection;
$http = $http ?: new \Workerman\Http\Client();
$http->get('https://example.com/', function ($response) use ($connection) {
$connection->send(new Chunk($response->getBody()));
$connection->send(new Chunk('')); // Sending an empty chunk denotes the end of the response
});
return response()->withHeaders([
"Transfer-Encoding" => "chunked",
]);
}
}
The above usage first returns an HTTP header with chunked format to the client, and then sends the data to the client in chunks, and of course, coroutine usage can also be referred to as shown above.
Note
The above code stores the client object in a static variable of the method scope for reuse, which can also be stored in a class's static member or global object.
Making Requests to the OpenAI API with Streaming Responses in Webman
Refer to https://www.workerman.net/plugin/157