Symfony2 - How to perform an external Request

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

提交回复
热议问题