【问题标题】:Routing HTTP (API) Calls via PHP通过 PHP 路由 HTTP (API) 调用
【发布时间】:2015-09-12 22:22:20
【问题描述】:

有没有办法通过 PHP “路由” HTTP (API) 调用?基本上我有3个系统。系统 A 可以访问系统 B,系统 B 可以访问系统 C。但是,系统 A 无法访问系统 C。是否可以轻松地将我的 API 调用路由到系统 B,它可以充当中间人并与系统 C 和 B 进行通信可以用调用结果回复A吗?

【问题讨论】:

  • 你的尝试看起来像……?

标签: php http-proxy


【解决方案1】:

您要创建的是一个代理。这可以用 PHP 很好地完成。以下代码是一个非常简单的代理实现,读取 POST 数据,将它们提交到不同的 URL,并将结果返回给原始客户端:

$targetUrl = 'https://www.example.com/api/foobar';
$headers = [];
$postData = file_get_contents('php://input');

foreach ($_SERVER as $key => $value)
{
    if (stripos($key, "HTTP_") === 0 && stripos($key, "Host") === false)
    {
        $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
        $headers[] = "$key: $value";
    }
}

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $targetUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_VERBOSE, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);

$response = curl_exec($curl);

if (curl_errno($curl))
    throw new \Exception(sprintf("Connection error %s: %s", curl_errno($curl), curl_error($curl)));

curl_close($curl);

echo gzdecode($response);

这只是一个例子,它做了几个假设(有效负载是 POST 数据,响应是 gzip 等)

随意调整代码以满足您的需求,或查看基于 PHP 代理的各种更高级的实现,例如https://github.com/jenssegers/php-proxy.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 2012-07-30
    • 1970-01-01
    • 2019-01-15
    • 2018-03-25
    • 2016-02-06
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多