Symfony2 : send a HTTP Request

后端 未结 6 723
旧巷少年郎
旧巷少年郎 2021-01-31 21:57

I am trying to make a HTTP Request from one of my controller to contact another URL, the goal being to contact another URL, and to simply print the HTML answer in my page. I tri

6条回答
  •  旧时难觅i
    2021-01-31 22:29

    EDIT: I made a GremoBuzzBundle for Buzz browser. It's similar to SensioBuzzBundle but it has some nice configuration options.

    I would suggest to use Buzz browser and dependency injection. Buzz is a wrapper around cURL or file_get_contents. Edit your deps file adding these lines:

    [Buzz]
        git=https://github.com/kriswallsmith/Buzz.git
        target=/buzz
    

    Then install vendors to actually download the library:

    php bin/vendors install
    

    Then add two services (src/YourCompany/YourBundle/Resources/config/services.yml):

    # cURL client for Buzz
    buzz.client.curl:
      class:  Buzz\Client\Curl
      public: false
      calls:
        - [setVerifyPeer, [false]]
    
    # Buzz browser
    buzz.browser:
      class:     Buzz\Browser
      arguments: ['@buzz.client.curl']
    

    The first service is the client (i prefer cURL over file_get_contents), the latter is the browser itself. The last step is to add one line of code in the autoloader (app/autoload.php):

    $loader->registerNamespaces(array(
        'Buzz' => __DIR__.'/../vendor/buzz/lib',
    ));
    

    Then you can get the service and user the browser in your controller code:

    $browser = $this->get('buzz.browser');
    $response = $browser->get('http://www.google.com');
    

提交回复
热议问题