RAW POST using cURL in PHP
如何使用cURL在PHP中进行RAW POST?
未经处理的原始帖子没有任何编码,我的数据存储在字符串中。 数据应采用以下格式:
1 2 3 4 5 6 7 8 | ... 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,使用文本/纯文本以及从
我刚刚找到了解决方案,可以回答我自己的问题,以防其他人偶然发现它。
1 2 3 4 5 6 7 8 9 | $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库实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | use GuzzleHttp\Client; use GuzzleHttp equestOptions; $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扩展名:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | $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); |
源代码