使用Symfony2,我需要访问基于HTTPS的外部API.
如何调用外部URI并管理响应以"播放"它.例如,要呈现成功还是失败消息?
我想的是(注意performRequest是一个完全发明的方法):
$response = $this -> performRequest("www.someapi.com?param1=A¶m2=B");
if ($response -> getError() == 0){
// Do something good
}else{
// Do something too bad
}
Run Code Online (Sandbox Code Playgroud)
我一直在阅读有关Buzz和其他客户的信息.但我想Symfony2应该能够自己做到.
Rob*_*ers 33
我建议使用CURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'www.someapi.com?param1=A¶m2=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);
Run Code Online (Sandbox Code Playgroud)
注意: Web服务器上的php必须php5-curl安装库.
假设API请求正在返回JSON数据,则此页面可能很有用.
这不使用任何特定于Symfony2的代码.可能有一个捆绑可以简化这个过程,但如果有,我不知道它.
Tho*_*ley 27
Symfony没有内置服务,但这是使用依赖注入框架创建自己的服务的绝佳机会.你在这里可以做的是编写一个服务来管理外部呼叫.我们将服务称为"http".
首先,用一个performRequest()方法编写一个类:
namespace MyBundle\Service;
class Http
{
public function performRequest($siteUrl)
{
// Code to make the external request goes here
// ...probably using cUrl
}
}
Run Code Online (Sandbox Code Playgroud)
将其注册为以下服务app/config/config.yml:
services:
http:
class: MyBundle\Service\Http
Run Code Online (Sandbox Code Playgroud)
现在您的控制器可以访问名为"http"的服务.Symfony在"容器"中管理此类的单个实例,您可以通过$this->get("http")以下方式访问它:
class MyController
{
$response = $this->get("http")->performRequest("www.something.com");
...
}
Run Code Online (Sandbox Code Playgroud)
Kam*_*nek 12
我所知道的最好的客户是:http://docs.guzzlephp.org/en/latest/
已经有捆绑将它集成到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');
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请访问:http://docs.guzzlephp.org/en/latest/index.html
Seb*_*oFr 10
https://github.com/sensio/SensioBuzzBundle似乎就是你要找的.
它实现了Kris Wallsmith buzz库来执行HTTP请求.
我会让你在github页面上阅读doc,用法非常基本:
$buzz = $this->container->get('buzz');
$response = $buzz->get('http://google.com');
echo $response->getContent();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53820 次 |
| 最近记录: |