Symfony2 - How to perform an external Request

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

    Symfony doesn't have a built-in service for this, but this is a perfect opportunity to create your own, using the dependency injection framework. What you can do here is write a service to manage the external call. Let's call the service "http".

    First, write a class with a performRequest() method:

    namespace MyBundle\Service;
    
    class Http
    {    
        public function performRequest($siteUrl)
        {
            // Code to make the external request goes here
            // ...probably using cUrl
        }
    }
    

    Register it as a service in app/config/config.yml:

    services:
        http:
            class: MyBundle\Service\Http
    

    Now your controller has access to a service called "http". Symfony manages a single instance of this class in the "container", and you can access it via $this->get("http"):

    class MyController
    {
        $response = $this->get("http")->performRequest("www.something.com");
    
        ...
    }
    
    0 讨论(0)
  • 2020-12-14 02:07

    I'd suggest using CURL:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'www.someapi.com?param1=A&param2=B');
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json')); // Assuming you're requesting JSON
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $response = curl_exec($ch);
    
    // If using JSON...
    $data = json_decode($response);
    

    Note: The php on your web server must have the php5-curl library installed.

    Assuming the API request is returning JSON data, this page may be useful.

    This doesn't use any code that is specific to Symfony2. There may well be a bundle that can simplify this process for you, but if there is I don't know about it.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-14 02:16

    https://github.com/sensio/SensioBuzzBundle seems to be what you are looking for.

    It implements the Kris Wallsmith buzz library to perform HTTP requests.

    I'll let you read the doc on the github page, usage is pretty basic:

    $buzz = $this->container->get('buzz');
    
    $response = $buzz->get('http://google.com');
    
    echo $response->getContent();
    
    0 讨论(0)
  • 2020-12-14 02:17

    Symfony does not have its own rest client, but as you already mentioned there are a couple of bundles. This one is my prefered one:

    https://github.com/CircleOfNice/CiRestClientBundle

    $restClient = $this->container->get('ci.restclient');
    
    $restClient->get('http://www.someUrl.com');
    $restClient->post('http://www.someUrl.com', 'somePayload');
    $restClient->put('http://www.someUrl.com', 'somePayload');
    $restClient->delete('http://www.someUrl.com');
    $restClient->patch('http://www.someUrl.com', 'somePayload');
    
    $restClient->head('http://www.someUrl.com');
    $restClient->options('http://www.someUrl.com', 'somePayload');
    $restClient->trace('http://www.someUrl.com');
    $restClient->connect('http://www.someUrl.com');
    

    You send the request via

    $response = $restclient->get($url); 
    

    and get a Symfony response object. Then you can get the status code via

    $httpCode = $response-> getStatusCode();
    

    Your code would look like:

    $restClient = $this->container->get('ci.restclient');
    if ($restClient->get('http://www.yourUrl.com')->getStatusCode !== 200) {
        // no error
    } else {
        // error
    }
    
    0 讨论(0)
提交回复
热议问题