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

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

Declaration

<?php Swoole\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

Swoole\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 Swoole was compiled with SSL support.


Structure

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

<?php

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

...

object(Swoole\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 Swoole\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 Swoole\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 August 31, 2022