【问题标题】:SilverStripe: How do I make HTTP Request to another website?SilverStripe:如何向另一个网站发出 HTTP 请求?
【发布时间】:2023-11-27 19:40:01
【问题描述】:

我正在尝试在控制器方法中向另一个网站发出 HTTP 请求。我搜索了解决方案,但找不到任何可行的示例。

这是我的代码:

$r = new HttpRequest('http://community.bba.org/home', HttpRequest::METH_GET);
$r->addQueryData(array('SessionID' => $arrGetParams['SessionID']));
try {
    $r->send();
} catch (HttpException $ex) {}

我收到以下错误:

致命错误:在第 215 行的 C:\wamp\www\abb\mysite\code\form\ALoginForm.php 中找不到类 'HttpRequest'

我怎样才能使这个 HTTP 请求工作?

我在 Windows 7 机器上的 WAMP 上使用 SilverStripe。

【问题讨论】:

  • 一个空的 catch 块肯定是得不到帮助的。
  • “那没用” - 发生了什么?错误消息、日志文件、行为描述可能有助于诊断问题
  • 添加了错误信息,我认为在“SilverStripe”中还有另一种方法可以发出http请求

标签: php httprequest silverstripe


【解决方案1】:

http://php.net/manual/en/http.install.php

这个 » PECL 扩展不与 PHP 捆绑在一起。

此问题与 SilverStripe 本身无关。您需要安装该模块,或使用 curl(wampserver 确实与该模块捆绑在一起)。 How to enable curl in Wamp server

http://docs.silverstripe.org/en/3.1/developer_guides/integration/restfulservice/,但我不推荐。

【讨论】:

    【解决方案2】:

    向外部站点或资源发出请求的内置方法是使用RestfulService

    文档在这里:http://docs.silverstripe.org/en/3.1/developer_guides/integration/restfulservice/

    典型用法:

    $service = new RestfulService('http://community.bba.org/home', 1200); //domain, cache duration
    $service->setQueryString(array(
        'SessionID' => $arrGetParams['SessionID'],
    ));
    $response = $service->request();
    $body = $response->getBody();
    

    如果你想使用 PHP 的 HTTPRequest,你必须安装 http 扩展 (http://php.net/manual/en/http.install.php)

    【讨论】:

    • 谢谢,现在我可以看到响应了,我有一个场景,我需要在另一个网站上传递查询字符串值,这会在该网站上创建会话,如果我有,我可以这样做在我的网页上隐藏 iframe。有没有办法通过发出http请求在php代码中实现这一点,我用你的代码尝试过,但是当我在同一个浏览器中访问该网站时它不会创建会话?
    • 我认为您需要为此提出一个新问题。但是您将无法以这种方式在用户的浏览器中启动愤怒会话。
    最近更新 更多