如何向外部 API 发送请求
我是 Symfony2 的新手,我正在尝试发送一个
new Request()
外部 API。这就是我所拥有的,但我不知道它是否正确使用内置的请求/响应库。
$request = new Request('https://myservice.com/apimethod?foo=bar', 'GET');
谁能告诉我,如果我尝试调用的 API 存在,这是否会返回响应?!如果不是,我做错了什么?
I am new to Symfony2 and I'm trying to send a
new Request()
to and external API. This is what I have but I don't know if it is correct use of the built in request/response library.
$request = new Request('https://myservice.com/apimethod?foo=bar', 'GET');
Can anyone tell me if this will return a response provided the API I'm trying to call exists?! If not, what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Symfony2 中,Request 类表示向您的站点发出的 HTTP 请求。基本上,如果您访问 www.yoursite.com/someaction,Symfony 会实例化一个 Symfony\Component\HttpFoundation\Request 对象。该对象包含可用于检查 HTTP 请求的方法(例如查看它是否包含 GET 或 POST 变量。)
这是 Symfony 和 HTTP 基础。我还建议查看 Request 的源代码,以了解它到底能做什么。
为了实现您在示例中尝试执行的操作,您需要使用 cURL。我个人在 cURL 之上使用了一个包装类,您可以在此处找到它。
希望这有帮助。
In Symfony2, the Request class represents an HTTP request made to your site. Basically, if you go to
www.yoursite.com/someaction
Symfony instantiates aSymfony\Component\HttpFoundation\Request
object. This object contains methods that you can use to examine the HTTP request (such as seeing if it contains GET or POST variables.)This is a good explanation of Symfony and HTTP fundamentals. I also recommend looking at the source code for Request to see exactly what it can do.
In order to achieve what you're trying to do in your example, you'd need to use cURL. I personally use a wrapper class on top of cURL that you can find here.
Hope this helps.
https://github.com/CircleOfNice/CiRestClientBundle
这是向外部 API 发送请求的最简单方法。它以函数的形式提供所有 http 方法,并且易于使用。
如果您只想对 CRUD 实体使用休息客户端,那么我认为您应该看看
https://github.com /CircleOfNice/DoctrineRestDriver
可以帮助您摆脱手动发送请求和映射响应的麻烦,因为 Doctrine 正在为您完成这项工作。
https://github.com/CircleOfNice/CiRestClientBundle
It's the easiest way to send a request to an external API. It provides all http methods as functions and is easy to use.
If you want to use rest clients just to CRUD entities then I think you should have a look at
https://github.com/CircleOfNice/DoctrineRestDriver
which helps you to get rid of manually sending requests and mapping responses because Doctrine is doing the job for you.
其他人回答了这样的问题: https://stackoverflow.com/a/10715549/2306587
你没有依赖 cURL 发出外部请求。有一个 Symfony-Bundle 可以处理这个问题: http://knpbundles.com/sonata-project/SonataGoutteBundle
Someone else answered a question like this: https://stackoverflow.com/a/10715549/2306587
You don't have to rely on cURL to make an external request. There is a Symfony-Bundle who can handle that: http://knpbundles.com/sonata-project/SonataGoutteBundle
使用此处中的 Guzzle。
示例:
Use Guzzle from here.
Exemple: