PHP post 请求 file_get_content

PHP post request with file_get_content

请有人帮助我

我正在尝试 POST 使用 file_get_contents 的请求,但我收到了 415 代码错误消息。我不是专业开发人员,我想知道我的源代码中有什么问题。这是我的问题:

  1. 我生成一个令牌,它是第二个请求的参数
  2. 生成的令牌必须用于 POST 请求

我收到一条 415 错误代码消息。我不知道如何更正该来源

$tok=file_get_contents('https://restapi.bulksmsonline.com/rest/api/v1/sms/gettoken/username/xxxx/password/xxxx');
$toke =json_decode($tok, true);
$token=$toke['token'];

$data = json_encode(
    array(
        'from' => 'TEST',
        'to' => '335546821546',
        'type'=> 'Text',
        'content'=> 'Test',
        'sendDateTime'=> '2020/07/07'
        )
);

$options = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => "Authorization Token " . base64_encode("$token"),
        'content' => $data
    )
);

$context = stream_context_create($options);

$url = 'https://restapi.bulksmsonline.com/rest/api/v1/sms/send';

$result = file_get_contents($url,false,$context);

如果您在 post 调用中获得令牌并遇到问题,那么我注意到您错过了一些请求 Headers:

喜欢 Content-type、Content-length,我检查了不同的 URL,它对我有用,试试吧

<?php
    $tok=file_get_contents('https://restapi.bulksmsonline.com/rest/api/v1/sms/gettoken/username/xxxx/password/xxxx');
    $toke =json_decode($tok, true);
    $token=$toke['token'];

    $data = json_encode(
        array(
            'from' => 'TEST',
            'to' => '335546821546',
            'type'=> 'Text',
            'content'=> 'Test',
            'sendDateTime'=> '2020/07/07'
            )
    );

    $options = array('http' =>
        array(
            'method'  => 'POST',
            'header' => "Content-type: application/json\r\n" .
                        "Content-length: " . strlen($data) . "\r\n" .
                        "Authorization Token: " . base64_encode("$token") . "\r\n",
            'content' => $data
        )
    );

    $context = stream_context_create($options);

    $url = 'https://restapi.bulksmsonline.com/rest/api/v1/sms/send';

    $result = file_get_contents($url,false,$context);
    var_dump($result);