Symfony2 - 如何执行外部请求

时间:2012-10-25 15:32:53

标签: php http symfony

使用Symfony2,我需要访问基于HTTPS的外部API。

如何调用外部URI并管理响应以“播放”它。例如,要呈现成功还是失败消息?

我正在想类似的事情(请注意,performRequest是一种完全发明的方法):

$response = $this -> performRequest("www.someapi.com?param1=A&param2=B");

if ($response -> getError() == 0){
    // Do something good
}else{
    // Do something too bad
}

我一直在阅读有关Buzz和其他客户的信息。但我想Symfony2应该可以自己做。

6 个答案:

答案 0 :(得分:33)

我建议使用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);

注意:您的网络服务器上的php必须安装php5-curl库。

假设API请求返回JSON数据,this page可能很有用。

这不使用任何特定于Symfony2的代码。可能有一个捆绑可以为您简化此过程,但如果有,我不知道它。

答案 1 :(得分:26)

Symfony没有为此提供内置服务,但这是使用依赖注入框架创建自己的服务的绝佳机会。你在这里可以做的是编写一个服务来管理外部呼叫。我们来打电话给服务" http"。

首先,使用performRequest()方法编写一个类:

namespace MyBundle\Service;

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

将其注册为app/config/config.yml中的服务:

services:
    http:
        class: MyBundle\Service\Http

现在您的控制器可以访问名为" http"的服务。 Symfony在"容器"中管理此类的单个实例,您可以通过$this->get("http")访问它:

class MyController
{
    $response = $this->get("http")->performRequest("www.something.com");

    ...
}

答案 2 :(得分:12)

我认识的最佳客户是:http://docs.guzzlephp.org/en/latest/

已经有捆绑将它集成到Symfony2项目中: 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');

可在以下网址找到更多信息:http://docs.guzzlephp.org/en/latest/index.html

答案 3 :(得分:10)

https://github.com/sensio/SensioBuzzBundle似乎就是你要找的东西。

它实现了Kris Wallsmith buzz库来执行HTTP请求。

我会让你阅读github页面上的文档,用法很基本:

$buzz = $this->container->get('buzz');

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

echo $response->getContent();

答案 4 :(得分:3)

Symfony没有自己的休息客户端,但正如您已经提到的那样,有几个捆绑包。这是我的首选:

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');

您通过

发送请求
$response = $restclient->get($url); 

并获取Symfony响应对象。 然后,您可以通过

获取状态代码
$httpCode = $response-> getStatusCode();

您的代码如下:

$restClient = $this->container->get('ci.restclient');
if ($restClient->get('http://www.yourUrl.com')->getStatusCode !== 200) {
    // no error
} else {
    // error
}

答案 5 :(得分:0)

使用HttpClient类创建发出请求的低级HTTP客户端,例如以下GET请求:

    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', ...]

这与Symfony 5兼容。有关此主题的Symfony手册:The HttpClient Component

相关问题