Symfony2 - How to perform an external Request

后端 未结 6 1655
走了就别回头了
走了就别回头了 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:13

    Best client that I know is: http://docs.guzzlephp.org/en/latest/

    There is already bundle that integrates it into Symfony2 project: https://github.com/8p/GuzzleBundle

    $client   = $this->get('guzzle.client');
    
    // send an asynchronous request.
    $request = $client->createRequest('GET', 'http://httpbin.org', ['future' => true]);
    // callback
    $client->send($request)->then(function ($response) {
        echo 'I completed! ' . $response;
    });
    
    // optional parameters
    $response = $client->get('http://httpbin.org/get', [
        'headers' => ['X-Foo-Header' => 'value'],
        'query'   => ['foo' => 'bar']
    ]);
    $code = $response->getStatusCode();
    $body = $response->getBody();
    
    // json response
    $response = $client->get('http://httpbin.org/get');
    $json = $response->json();
    
    // extra methods
    $response = $client->delete('http://httpbin.org/delete');
    $response = $client->head('http://httpbin.org/get');
    $response = $client->options('http://httpbin.org/get');
    $response = $client->patch('http://httpbin.org/patch');
    $response = $client->post('http://httpbin.org/post');
    $response = $client->put('http://httpbin.org/put');
    

    More info can be found on: http://docs.guzzlephp.org/en/latest/index.html

提交回复
热议问题