【问题标题】:RAW POST using cURL in PHP在 PHP 中使用 cURL 的 RAW POST
【发布时间】:2010-10-26 15:58:26
【问题描述】:

如何使用 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 发送原始数据吗?

【问题讨论】:

    标签: php post curl put


    【解决方案1】:

    我刚刚找到了解决方案,有点像回答我自己的问题,以防其他人偶然发现它。

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

    【讨论】:

    • php 会为你设置 content-length 标题还是你也应该设置它?
    • 我根本无法让它工作。我有一个试图将原始数据发布到的页面。该页面将其接收到的所有原始数据记录到数据库表中。根本没有新行。你知道自 09 年以来这里有什么变化吗?
    • 这对我有用,无需指定任何 HTTP 标头。
    • 我刚刚意识到 body goes here 可以包含任何有效的 json 字符串。
    • 此原始帖子有 2G 限制。如果您尝试发送大于 2G 的文件,它们将被截断回 2G。它是正在加载的字符串类型的限制。
    【解决方案2】:

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

    Source code

    【讨论】:

      猜你喜欢
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多