php Symfony2:发送 HTTP 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10620024/
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-24 22:38:32  来源:igfitidea点击:

Symfony2 : send a HTTP Request

phphtmlhttpsymfonyhttprequest

提问by Gabriel Theron

I am trying to make a HTTP Request from one of my controller to contact another URL, the goal being to contact another URL, and to simply print the HTML answer in my page. I tried :

我试图从我的一个控制器发出 HTTP 请求以联系另一个 URL,目标是联系另一个 URL,并简单地在我的页面中打印 HTML 答案。我试过 :

$r = new Request();
$r->create('http://www.google.com', 'GET');

return $this->render(...mytemplate..., array('name' => $r->getContent());



My template is simply printing the variable "name".
Now when I do that, nothing is returned. It seems to me that the request is never sent, which is why nothing is returned.



我的模板只是打印变量“名称”。
现在,当我这样做时,什么也没有返回。在我看来,请求从未发送过,这就是为什么没有返回任何内容。

My question is : how do I send the request and get the content of the response?

我的问题是:如何发送请求并获取响应的内容?

Thanks in advance.

提前致谢。

回答by gremo

EDIT: I made a GremoBuzzBundlefor Buzz browser. It's similar to SensioBuzzBundlebut it has some nice configuration options.

编辑:我为 Buzz 浏览器制作了一个GremoBuzzBundle。它类似于SensioBuzzBundle,但它有一些不错的配置选项。

I would suggest to use Buzz browserand dependency injection. Buzz is a wrapper around cURL or file_get_contents. Edit your depsfile adding these lines:

我建议使用Buzz 浏览器和依赖注入。Buzz 是 cURL 或 file_get_contents 的包装器。编辑您的deps文件,添加以下几行:

[Buzz]
    git=https://github.com/kriswallsmith/Buzz.git
    target=/buzz

Then install vendors to actually download the library:

然后安装供应商以实际下载库:

php bin/vendors install

Then add two services(src/YourCompany/YourBundle/Resources/config/services.yml):

然后添加两个服务( src/YourCompany/YourBundle/Resources/config/services.yml):

# cURL client for Buzz
buzz.client.curl:
  class:  Buzz\Client\Curl
  public: false
  calls:
    - [setVerifyPeer, [false]]

# Buzz browser
buzz.browser:
  class:     Buzz\Browser
  arguments: ['@buzz.client.curl']

The first service is the client (i prefer cURL over file_get_contents), the latter is the browser itself. The last step is to add one line of code in the autoloader(app/autoload.php):

第一个服务是客户端(我更喜欢 cURL 而不是 file_get_contents),后者是浏览器本身。最后一步是在自动加载器( app/autoload.php) 中添加一行代码:

$loader->registerNamespaces(array(
    'Buzz' => __DIR__.'/../vendor/buzz/lib',
));

Then you can get the service and user the browser in your controllercode:

然后,您可以在控制器代码中获取服务并使用浏览器:

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

回答by Peter Bailey

Two problems.

两个问题。

First of all, that's not the proper usage of Symfony\Component\HttpFoundation\Request::create(), which is a static initializer/factory of sorts. Your code should look like this

首先,这不是 的正确用法Symfony\Component\HttpFoundation\Request::create(),它是某种静态初始值设定项/工厂。你的代码应该是这样的

$r = Request::create( 'http://www.google.com', 'GET' );

Now you have a proper Request object. However, this is irrelevant which is your second problem: that's not how Symfony's request object is designed to work. Its purpose is not for executingHTTP requests, its for representingthem as objects in the framework.

现在你有了一个合适的 Request 对象。然而,这与您的第二个问题无关:这不是 Symfony 的请求对象的设计方式。它的目的不是为了执行HTTP 请求,而是为了将它们表示为框架中的对象。

Long story short, you can't do it that way. Perhaps you can use cURL to scrape the pageyou want?

长话短说,你不能那样做。也许您可以使用 cURL 来抓取您想要的页面

回答by Kamil Adryjanek

I would recommend you using GuzzleHttp Client - best client that I know: http://docs.guzzlephp.org/en/latest/

我建议您使用 GuzzleHttp Client - 我所知道的最好的客户端:http://docs.guzzlephp.org/en/latest/

There is already nice bundle that integrates it into Symfony2 project: https://github.com/8p/GuzzleBundle

已经有很好的包将它集成到 Symfony2 项目中:https: //github.com/8p/GuzzleBundle

Then from your controller you can call:

然后从你的控制器你可以调用:

$client   = $this->get('guzzle.client');

// GET request with parameters
$response = $client->get('http://httpbin.org/get', [
    'headers' => ['X-Foo-Header' => 'value'],
    'query'   => ['foo' => 'bar']
]);
$code = $response->getStatusCode();
$body = $response->getBody();

More info can be found on: http://docs.guzzlephp.org/en/latest/index.html

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

回答by koral

Why not use curl? From PHP manual

为什么不使用卷曲?来自PHP 手册

$ch = curl_init("http://www.example.com/");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

result = curl_exec($ch);
curl_close($ch);

回答by Mauro Colella

Apparently, you can use Symfony's built-in HTTP client. See: http://api.symfony.com/2.0/Symfony/Component/HttpKernel.html

显然,您可以使用 Symfony 的内置 HTTP 客户端。请参阅:http: //api.symfony.com/2.0/Symfony/Component/HttpKernel.html

The following is a very crude codebase, using Silex (built on top of Symfony). It simply instantiates a new HTTP client.

以下是一个非常粗略的代码库,使用 Silex(建立在 Symfony 之上)。它只是实例化一个新的 HTTP 客户端。

<?php
require_once __DIR__ . '/silex/vendor/autoload.php';

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Client;
//use Symfony\Component\HttpFoundation\Response;

$dispatcher = new EventDispatcher();
$resolver = new ControllerResolver();
$kernel = new HttpKernel( $dispatcher, $resolver );

$client = new Client( $kernel );
var_dump( $client );

?>

?>

You also have a detailed example of a HTTP client for Symfony2 as part of the unit testing documentation. See: http://symfony.com/doc/current/book/testing.html

作为单元测试文档的一部分,您还有一个用于 Symfony2 的 HTTP 客户端的详细示例。请参阅:http: //symfony.com/doc/current/book/testing.html

BUT (edit)these clients are local to your app. The concepts illustrated here are better implemented with the BrowserKit component of Symfony2. A headless browser within Symfony.

但是(编辑)这些客户端在您的应用程序中是本地的。此处说明的概念可以通过 Symfony2 的 BrowserKit 组件更好地实现。Symfony 中的无头浏览器。

Better even, use Goutte for requests to external websites. See https://github.com/FriendsOfPHP/Gouttefor details.

更好的是,使用 Goutte 请求外部网站。有关详细信息,请参阅https://github.com/FriendsOfPHP/Goutte

回答by Tobias

https://github.com/CircleOfNice/CiRestClientBundle

https://github.com/CircleOfNice/CiRestClientBundle

Nice API for easy usage of the curl library and it returns a symfony response instead of a string result

用于轻松使用 curl 库的漂亮 API,它返回一个 symfony 响应而不是字符串结果

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