如何向外部API发送请求

tra*_*ega 15 api syntax http request symfony

我是Symfony2的新手,我正在尝试发送一个

new Request()
Run Code Online (Sandbox Code Playgroud)

和外部API.这就是我所拥有的,但我不知道它是否正确使用内置的请求/响应库.

$request = new Request('https://myservice.com/apimethod?foo=bar', 'GET'); 
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我,如果我试图调用的API存在,这是否会返回响应?!如果没有,我做错了什么?

Ste*_*nte 18

在Symfony2中,Request类表示对您的站点发出的HTTP请求.基本上,如果你去www.yoursite.com/someactionSymfony实例化一个Symfony\Component\HttpFoundation\Request对象.此对象包含可用于检查HTTP请求的方法(例如,查看它是否包含GET或POST变量.)

这是对Symfony和HTTP基础知识的一个很好的解释.我还建议查看Request的源代码,看看它能做些什么.

为了实现您在示例中尝试执行的操作,您需要使用cURL.我个人在cURL上使用了一个包装类,你可以在这里找到它.

希望这可以帮助.

  • +1但是为了提出请求,我通常会使用Buzz.它是一个干净,简单和轻量级的HTTP库:https://github.com/kriswallsmith/Buzz (4认同)

Tob*_*ias 7

https://github.com/CircleOfNice/CiRestClientBundle

这是向外部API发送请求的最简单方法.它提供所有http方法作为函数,并且易于使用.

$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');
Run Code Online (Sandbox Code Playgroud)

如果你想只使用CRUD实体的休息客户端,那么我认为你应该看看

https://github.com/CircleOfNice/DoctrineRestDriver

这可以帮助您摆脱手动发送请求和映射响应,因为Doctrine正在为您完成工作.

// Sends a GET request to http://$driverUrl/@TableAnnotation/1 and returns a valid MyEntity Entity
$entity = $em->find("Some\Namespace\MyEntity", 1);
Run Code Online (Sandbox Code Playgroud)