如何使用 cURL 在 PHP 中进行 RAW POST?
未经任何编码的原始帖子,我的数据存储在一个字符串中。数据格式应如下所示:
... usual HTTP header ...
Content-Length: 1039
Content-Type: text/plain
89c5fdataasdhf kajshfd akjshfksa hfdkjsa falkjshfsa
ajshd fkjsahfd lkjsahflksahfdlkashfhsadkjfsalhfd
ajshdfhsafiahfiuwhflsf this is just data from a string
more data kjahfdhsakjfhsalkjfdhalksfd
一种选择是手动编写要发送的整个 HTTP 标头,但这似乎不太理想。
无论如何,我可以只将选项传递给 curl_setopt() 说使用 POST、使用 text/plain 并从 $variable
发送原始数据吗?
我刚刚找到了解决方案,有点回答我自己的问题,以防其他人偶然发现它。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec($ch);
使用 Guzzle 库实现:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL 扩展:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);