【问题标题】:PHP post request with file_get_content带有 file_get_content 的 PHP 发布请求
【发布时间】:2020-07-08 12:05:30
【问题描述】:

请有人帮助我

我正在尝试使用file_get_contentsPOST 发送请求,但我收到了 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);

【问题讨论】:

  • 415 不支持的媒体类型 (RFC 7231)
  • 你得到$token了吗?
  • Content-length, Content-type 都缺少请求头
  • 是的@VishalSolanki 我得到了$token,但我不知道我是否正确使用它。我必须如何更改内容类型和内容长度?
  • 检查我的答案

标签: php post token file-get-contents


【解决方案1】:

如果您仅在通话后获得令牌并面临问题,那么我注意到您错过了一些请求标头:

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

【讨论】:

  • 嗨@VishalSolanki 这是结果:failed to open stream: Warning: file_get_contents(https://restapi.bulksmsonline.com/rest/api/v1/sms/send): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /htdocs/vishal.php on line 30 bool(false) 这是第 30 行:$result = file_get_contents($url,false,$context);
  • 嗨 @vishalSolanki 我很困惑这里是 API bulksmsonline.com/developers Restful API 部分的开发页面。感谢您的帮助
  • 你应该使用 php curl
猜你喜欢
  • 1970-01-01
  • 2017-05-25
  • 2015-06-24
  • 2015-10-19
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多