php Symfony2 - 如何执行外部请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13072097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:44:50  来源:igfitidea点击:

Symfony2 - How to perform an external Request

phphttpsymfony

提问by ElPiter

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. For example, to render a success or a failure message?

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

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. But I guess that Symfony2 should be able to do it by its own.

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

回答by RobMasters

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-curllibrary installed.

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

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

假设 API 请求返回 JSON 数据,此页面可能有用。

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.

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

回答by Thomas Kelley

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".

Symfony 没有为此提供内置服务,但这是使用依赖项注入框架创建自己的服务的绝佳机会。您在这里可以做的是编写一个服务来管理外部调用。让我们将服务称为“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". Symfony manages a single instance of this class in the "container", and you can access it via $this->get("http"):

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

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

    ...
}

回答by Kamil Adryjanek

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

回答by SebScoFr

https://github.com/sensio/SensioBuzzBundleseems 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();

回答by Tobias

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:

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

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. Then you can get the status code via

并获得一个 Symfony 响应对象。然后您可以通过以下方式获取状态代码

$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
}

回答by Ali

Use the HttpClientclass 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 组件