使用cURL在PHP中发送原始POST请求

156

如何使用cURL在PHP中进行原始POST请求?

所谓的原始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的原始数据?

2个回答

285

我刚找到了解决方案,回答自己的问题以便其他人也能看到。

$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);

4
PHP会自动设置content-length头部吗?还是我需要自己设置? - Eric Bloch
3
我完全无法使它工作。我有一个页面,试图将原始数据发布到该页面。该页面将所有接收到的原始数据记录到数据库表中。但是没有任何新行。您知道自从2009年以来这里有没有发生任何变化吗? - James
1
这对我有效,而不需要指定任何HTTP头。 - xryl669
16
我刚意识到 "body goes here" 可以包含任何有效的 JSON 字符串。 - shasi kanth
2
此原始帖子有2G的限制。如果您尝试发送大于2G的文件,它们将被截断为2G。这是由于加载字符串类型的限制。 - Kaden Yealy
显示剩余5条评论

9

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);

源代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接