OpenSwoole\Coroutine\Http\Client::__construct(...)

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Coroutine\Http\Client::__construct(string $host, int $port, bool $ssl = false)

Parameters

host

Host name of the remote server or IP address. A DNS name will automatically be resolved.

port

Port of the remote server, normally uses 80 for HTTP services and 443 for HTTPS services.

ssl

If SSL should be enabled or not, SSL should be enabled if the remote service is using HTTPS.

Return

OpenSwoole\Coroutine\Http\Client

Coroutine HTTP Client


Description

Create a new HTTP Client within a co::run coroutine context.

When specifying the host you can add the protocol of the host like http:// or https://. There is also support for Unix Sockets like unix://tmp/your_file.sock.

Note: HTTPS support is only available if OpenSwoole was compiled with SSL support.


Structure

The structure of the HTTP Client object before execution of any requests:

<?php

var_dump(new OpenSwoole\Coroutine\Http\Client('swoole.co.uk', 443, true));

...

object(OpenSwoole\Coroutine\Http\Client)#3 (18) {
  ["errCode"]=>
  int(0)
  ["errMsg"]=>
  string(0) ""
  ["connected"]=>
  bool(false)
  ["host"]=>
  string(12) "swoole.co.uk"
  ["port"]=>
  int(443)
  ["ssl"]=>
  bool(true)
  ["setting"]=>
  NULL
  ["requestMethod"]=>
  NULL
  ["requestHeaders"]=>
  NULL
  ["requestBody"]=>
  NULL
  ["uploadFiles"]=>
  NULL
  ["downloadFile"]=>
  NULL
  ["downloadOffset"]=>
  int(0)
  ["statusCode"]=>
  int(0)
  ["headers"]=>
  NULL
  ["set_cookie_headers"]=>
  NULL
  ["cookies"]=>
  NULL
  ["body"]=>
  string(0) ""
}

Example

Using a parsed URL host (domain name) and path

<?php
use OpenSwoole\Coroutine\HTTP\Client;

co::run(function()
{
  $urlInfo = parse_url('https://swoole.co.uk');

  $host = $urlInfo['host'];
  $path = $urlInfo['path'];

  $client = new Client($host);

  $client->setHeaders([
      'Host' => $host,
      "User-Agent" => 'Chrome/49.0.2587.3',
      'Accept' => 'text/html,application/xhtml+xml,application/xml',
      'Accept-Encoding' => 'gzip',
  ]);

  $client->set(['timeout' => 1]);

  $client->get($path);

  echo $client->body;

  $client->close();
});

Using a direct IP and Port

<?php

use OpenSwoole\Coroutine\Http\Client;

co::run(function()
{
  $client = new Client('127.0.0.1', 80);

  $client->setHeaders([
      'Host' => 'localhost',
      'User-Agent' => 'Chrome/49.0.2587.3',
      'Accept' => 'text/html,application/xhtml+xml,application/xml',
      'Accept-Encoding' => 'gzip',
  ]);

  $client->set(['timeout' => 1]);

  $client->get('/index.php');

  echo $client->body;

  $client->close();
});
Last updated on September 1, 2022