Symfony2:发送HTTP请求 [英] Symfony2 : send a HTTP Request

查看:673
本文介绍了Symfony2:发送HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 :

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

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





我的模板只是打印变量name。

现在当我这样做时,没有返回。在我看来,请求永远不会被发送,这就是为什么没有返回。



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?

提前致谢。

推荐答案

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

EDIT: I made a GremoBuzzBundle for Buzz browser. It's similar to SensioBuzzBundle but it has some nice configuration options.

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

I would suggest to use Buzz browser and dependency injection. Buzz is a wrapper around cURL or file_get_contents. Edit your deps file adding these lines:

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

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

Then install vendors to actually download the library:

php bin/vendors install

然后添加两项服务 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']

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

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):

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

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

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

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

这篇关于Symfony2:发送HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆