NativeHttpClient example

class Psr18ClientTest extends TestCase
{
    public static function setUpBeforeClass(): void
    {
        TestHttpServer::start();
    }

    public function testSendRequest()
    {
        $factory = new Psr17Factory();
        $client = new Psr18Client(new NativeHttpClient()$factory$factory);

        $response = $client->sendRequest($factory->createRequest('GET', 'http://localhost:8057'));

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame('application/json', $response->getHeaderLine('content-type'));

        $body = json_decode((string) $response->getBody(), true);

        $this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
    }

    


namespace Symfony\Component\HttpClient\Tests;

use Symfony\Component\HttpClient\NativeHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class NativeHttpClientTest extends HttpClientTestCase
{
    protected function getHttpClient(string $testCase): HttpClientInterface
    {
        return new NativeHttpClient();
    }

    public function testInformationalResponseStream()
    {
        $this->markTestSkipped('NativeHttpClient doesn\'t support informational status codes.');
    }

    public function testTimeoutOnInitialize()
    {
        $this->markTestSkipped('NativeHttpClient doesn\'t support opening concurrent requests.');
    }

    

        ]));
        $sut->lateCollect();
        $collectedData = $sut->getClients();
        self::assertCount(1, $collectedData['http_client']['traces']);
        $curlCommand = $collectedData['http_client']['traces'][0]['curlCommand'];
        self::assertNull($curlCommand);
    }

    private function httpClientThatHasTracedRequests($tracedRequests): TraceableHttpClient
    {
        $httpClient = new TraceableHttpClient(new NativeHttpClient());

        foreach ($tracedRequests as $request) {
            $response = $httpClient->request($request['method']$request['url']$request['options'] ?? []);
            $response->getContent(false); // disables exceptions from destructors         }

        return $httpClient;
    }
}
use Symfony\Contracts\HttpClient\Test\TestHttpServer;

class HttplugClientTest extends TestCase
{
    public static function setUpBeforeClass(): void
    {
        TestHttpServer::start();
    }

    public function testSendRequest()
    {
        $client = new HttplugClient(new NativeHttpClient());

        $response = $client->sendRequest($client->createRequest('GET', 'http://localhost:8057'));

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame('application/json', $response->getHeaderLine('content-type'));

        $body = json_decode((string) $response->getBody(), true);

        $this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
    }

    
foreach ($client->stream($response) as $chunk) {
            if ($chunk->isFirst()) {
                self::assertSame(500, $response->getStatusCode());
            }
        }
    }

    public function testRetryWithDnsIssue()
    {
        $client = new RetryableHttpClient(
            new NativeHttpClient(),
            new class(GenericRetryStrategy::DEFAULT_RETRY_STATUS_CODES, 0) extends GenericRetryStrategy {
                public function shouldRetry(AsyncContext $context, ?string $responseContent, ?TransportExceptionInterface $exception): ?bool
                {
                    $this->fail('should not be called');
                }
            },
            2,
            $logger = new TestLogger()
        );

        $response = $client->request('GET', 'http://does.not.exists/foo-bar');

        
public function testItResetsTraces()
    {
        $sut = new TraceableHttpClient(new MockHttpClient());
        $sut->request('GET', 'https://example.com/foo/bar');
        $sut->reset();
        $this->assertCount(0, $sut->getTracedRequests());
    }

    public function testStream()
    {
        $sut = new TraceableHttpClient(new NativeHttpClient());
        $response = $sut->request('GET', 'http://localhost:8057/chunked');
        $chunks = [];
        foreach ($sut->stream($response) as $r => $chunk) {
            $chunks[] = $chunk->getContent();
        }
        $this->assertSame($response$r);
        $this->assertGreaterThan(1, \count($chunks));
        $this->assertSame('Symfony is awesome!', implode('', $chunks));
    }

    public function testToArrayChecksStatusCodeBeforeDecoding()
    {


            @trigger_error('Configure the "curl.cainfo", "openssl.cafile" or "openssl.capath" php.ini setting to enable the CurlHttpClient', \E_USER_WARNING);
        }

        if ($amp) {
            return new AmpHttpClient($defaultOptions, null, $maxHostConnections$maxPendingPushes);
        }

        @trigger_error((\extension_loaded('curl') ? 'Upgrade' : 'Install').' the curl extension or run "composer require amphp/http-client:^4.2.1" to perform async HTTP operations, including full HTTP/2 support', \E_USER_NOTICE);

        return new NativeHttpClient($defaultOptions$maxHostConnections);
    }

    /** * Creates a client that adds options (e.g. authentication headers) only when the request URL matches the provided base URI. */
    public static function createForBaseUri(string $baseUri, array $defaultOptions = [], int $maxHostConnections = 6, int $maxPendingPushes = 50): HttpClientInterface
    {
        $client = self::create([]$maxHostConnections$maxPendingPushes);

        return ScopingHttpClient::forBaseUri($client$baseUri$defaultOptions);
    }
}
$body = '{ "SERVER_PROTOCOL": "HTTP/1.1", "SERVER_NAME": "127.0.0.1", "REQUEST_URI": "/", "REQUEST_METHOD": "GET", "HTTP_ACCEPT": "*/*", "HTTP_FOO": "baR", "HTTP_HOST": "localhost:8057" }';

        $client = new NativeHttpClient();

        switch ($testCase) {
            default:
                return new MockHttpClient(function Dstring $method, string $url, array $options) use ($client) {
                    try {
                        // force the request to be completed so that we don't test side effects of the transport                         $response = $client->request($method$url['buffer' => false] + $options);
                        $content = $response->getContent(false);

                        return new MockResponse($content$response->getInfo());
                    } catch (\Throwable $e) {
                        
Home | Imprint | This part of the site doesn't use cookies.