Symfony2 - How to perform an external Request

后端 未结 6 1634
走了就别回头了
走了就别回头了 2020-12-14 01:48

Using Symfony2, I need to access an external API based on HTTPS.

How can I call an external URI and manage the response to \"play\" with it. For example, to render a

6条回答
  •  有刺的猬
    2020-12-14 02:07

    Use the HttpClient class to create the low-level HTTP client that makes requests, like the following GET request:

        use Symfony\Component\HttpClient\HttpClient;
    
    $client = HttpClient::create();
    $response = $client->request('GET', 'https://api.github.com/repos/symfony/symfony-docs');
    
    $statusCode = $response->getStatusCode();
    // $statusCode = 200
    $contentType = $response->getHeaders()['content-type'][0];
    // $contentType = 'application/json'
    $content = $response->getContent();
    // $content = '{"id":521583, "name":"symfony-docs", ...}'
    $content = $response->toArray();
    // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]
    

    This is compatible with Symfony 5. Symfony Manual on this topic: The HttpClient Component

提交回复
热议问题