2011-11-02 40 views
13

我是新來的Symfony2,我嘗試發送如何將請求發送到外部API

new Request() 

來和外部API。這是我的,但我不知道是否正確使用內置的請求/響應庫。

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

任何人都可以告訴我,如果這將返回一個響應提供API我試圖調用存在?!如果不是,我做錯了什麼?

回答

17

在Symfony2中,Request類表示向您的站點發出的HTTP請求。基本上,如果你去www.yoursite.com/someaction Symfony實例化一個Symfony\Component\HttpFoundation\Request對象。此對象包含可用於檢查HTTP請求的方法(例如查看它是否包含GET或POST變量。)

這是對Symfony and HTTP fundamentals的很好的解釋。我還建議查看Request的源代碼,以確切瞭解它的功能。

爲了實現你想要在你的例子中做的事情,你需要使用cURL。我個人使用cURL頂層的包裝類,你可以找到here

希望這會有所幫助。

+4

+1,但製作我通常使用Buzz的請求。這是一個乾淨,簡單和輕量級的HTTP庫:https://github.com/kriswallsmith/Buzz –

+0

@kuba感謝您的鏈接。我今天開始使用Buzz,我喜歡它。我也很喜歡你的文章服務容器:) –

+0

我很高興我可以幫忙。乾杯! :) –

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

如果你想使用其他客戶只是CRUD實體話,我想你應該看看

https://github.com/CircleOfNice/DoctrineRestDriver

它可以幫助您擺脫手動發送請求和映射響應,因爲學說正在爲你做這項工作。

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

使用Gu from here

例:

$client = new \GuzzleHttp\Client(); 
$res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle'); 
echo $res->getStatusCode();