【发布时间】:2020-09-20 05:57:35
【问题描述】:
我目前有一个旧的 PHP 页面,它向外部 API 执行发布请求,但我想将其转换为 Guzzle 以整理它,但我不确定我是否在正确的行上。
PHP 发布
function http_post($server, $port, $url, $vars)
{
// get urlencoded vesion of $vars array
$urlencoded = "";
foreach ($vars as $Index => $Value)
$urlencoded .= urlencode($Index) . "=" . urlencode($Value) . "&";
$urlencoded = substr($urlencoded, 0, -1);
$headers = "POST $url HTTP/1.0\r\n";
$headers .= "Content-Type: application/x-www-form-urlencoded\r\n";
$headers .= "Host: secure.test.com\r\n";
$headers .= "Content-Length: " . strlen($urlencoded)
$fp = fsockopen($server, $port, $errno, $errstr, 20); // returns file pointer
if (!$fp) return "ERROR: fsockopen failed.\r\nError no: $errno - $errstr"; // if cannot open socket then display error message
fputs($fp, $headers);
fputs($fp, $urlencoded);
$ret = "";
while (!feof($fp)) $ret .= fgets($fp, 1024);
fclose($fp);
return $ret;
}
检索 PHP 响应
以下是您如何检索可以使用 $_POST 字段的响应
$response = http_post("https://secure.test", 443, "/callback/test.php", $_POST);
Guzzle 尝试 POST
$client = new Client();
$request = $client->request('POST','https://secure.test.com/callback/test.php', [
// not sure how to pass the $vars from the PHP file
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'Host' => 'secure.test.com'
]
]);
$request->getBody()->getContents();
Guzzle 尝试 GET
$client = new Client();
$request = $client->get('https://secure.test.com/callback/test.php');
$request->getBody()->getContents();
然后我将如何从响应中获取特定字段?
从我上面的尝试来看,我是在正确的路线上吗?
【问题讨论】: