Search code examples
phphttpclient

I'm trying PHP Amp client but it's not working, keeps returning error


I'm trying Amp client to return page content but it keeps failing. I've installed the package, and trying the example given by the docs.. but I can't figure out why it's not working. Here's the code:

namespace App\Http\Controllers;
use Amp\Http\Client\HttpClientBuilder;

use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
//use Illuminate\Http\Request;

class AmpConcurrentRequestsController extends Controller
{
    public function ampTest1()
    {
        $httpClient = HttpClientBuilder::buildDefault();


        $request = new Request('GET', 'http://example.com');
        $promise = $httpClient->request($request);

        /** @var Response $response */
        $response = Amp\wait($promise);


        $statusCode = $response->getStatus();
        $body = yield $response->getBody()->buffer();

    }
}

I get this error:

Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Generator given, called in C:\xampp\htdocs\laundarySaaS\vendor\laravel\framework\src\Illuminate\Http\Response.php on line 72


Solution

  • What eventually worked for me is below code.

    public function ampTest1()
        {
            // Create a new HTTP client
            $httpClient = HttpClientBuilder::buildDefault();
    
            // Send a GET request to the specified URL
            $request = new Request( 'https://example.com');
    
            $promise = $httpClient->request($request);
    
            /** @var Response $response */
            $response = Promise\wait($promise);
    
            // Get the response code
            $code = $response->getStatus();
    
            // Do something with the response code
            echo $code;
        }