简体   繁体   English

Symfony2 - 如何执行外部请求

[英]Symfony2 - How to perform an external Request

Using Symfony2, I need to access an external API based on HTTPS.使用Symfony2,我需要访问基于HTTPS 的外部API。

How can I call an external URI and manage the response to "play" with it.如何调用外部 URI 并管理对“播放”的响应。 For example, to render a success or a failure message?例如,要呈现成功或失败的消息?

I am thinking in something like (note that performRequest is a completely invented method):我在想这样的事情(请注意, performRequest 是一种完全发明的方法):

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

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

I have been reading about Buzz and other clients.我一直在阅读有关 Buzz 和其他客户的信息。 But I guess that Symfony2 should be able to do it by its own.但我想 Symfony2 应该可以自己做。

I'd suggest using CURL:我建议使用 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.注意:您的 Web 服务器上的 php 必须安装php5-curl库。

Assuming the API request is returning JSON data, this page may be useful.假设 API 请求返回 JSON 数据,此页面可能有用。

This doesn't use any code that is specific to Symfony2.这不使用任何特定于 Symfony2 的代码。 There may well be a bundle that can simplify this process for you, but if there is I don't know about it.很可能有一个包可以为您简化这个过程,但如果有的话,我不知道。

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. Symfony 没有为此提供内置服务,但这是使用依赖项注入框架创建自己的服务的绝佳机会。 What you can do here is write a service to manage the external call.您在这里可以做的是编写一个服务来管理外部调用。 Let's call the service "http".让我们将服务称为“http”。

First, write a class with a performRequest() method:首先,编写一个带有performRequest()方法的类:

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 :app/config/config.yml其注册为服务:

services:
    http:
        class: MyBundle\Service\Http

Now your controller has access to a service called "http".现在您的控制器可以访问名为“http”的服务。 Symfony manages a single instance of this class in the "container", and you can access it via $this->get("http") : Symfony 在“容器”中管理此类的单个实例,您可以通过$this->get("http")访问它:

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

    ...
}

Best client that I know is: http://docs.guzzlephp.org/en/latest/我所知道的最好的客户端是: http : //docs.guzzlephp.org/en/latest/

There is already bundle that integrates it into Symfony2 project: https://github.com/8p/GuzzleBundle已经有将它集成到 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');

More info can be found on: http://docs.guzzlephp.org/en/latest/index.html可以在以下位置找到更多信息: http : //docs.guzzlephp.org/en/latest/index.html

https://github.com/sensio/SensioBuzzBundle seems to be what you are looking for. https://github.com/sensio/SensioBuzzBundle似乎正是您要找的。

It implements the Kris Wallsmith buzz library to perform HTTP requests.它实现了 Kris Wallsmith buzz 库来执行 HTTP 请求。

I'll let you read the doc on the github page, usage is pretty basic:我会让你阅读 github 页面上的文档,用法非常基本:

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

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

echo $response->getContent();

Symfony does not have its own rest client, but as you already mentioned there are a couple of bundles. Symfony 没有自己的 rest 客户端,但正如您已经提到的,有几个包。 This one is my prefered one:这是我的首选:

https://github.com/CircleOfNice/CiRestClientBundle 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.并获得一个 Symfony 响应对象。 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
}

Use the HttpClient class to create the low-level HTTP client that makes requests, like the following GET request:使用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', ...]

This is compatible with Symfony 5. Symfony Manual on this topic: The HttpClient Component这与 Symfony 5 兼容。 关于这个主题的 Symfony 手册: HttpClient 组件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM