dq8081 2018-05-10 11:29
浏览 280

PHP cURL - json请求的模式不正确

I'm trying to implement following cURL request in php:

curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: login:password" \
-d '{"phone": "+48667421797", "msg": "Great app! Thank you!"}' \
https://some.endpoint.url

It works fine in console, I also managed to use this request in tools like postman/insomnia.

But when I try to implement it in PHP like that:

    $fields = [
        'phone' => $number,
        'msg'   => $msg,
    ];

    $data = json_encode($fields);

    $headers = [
        'Content-Type: application/json',
        'Authorization: login:password'
    ];

    $ch = curl_init($url);

    curl_setopt($ch,CURLOPT_POST, 1);                                                    
    curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);

    curl_setopt($ch, CURLOPT_URL, config('kajaki.sms_url'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);


    $response = curl_exec($ch);

    curl_close($ch);

I get 400: Incorrect schema which AFAIK indicates, that the request is not being sent as valid JSON request.

What is wrong? How can I send this request correctly as a JSON?

Unfortunately this API does not provide any documentation.

  • 写回答

2条回答

  • doutao6653 2018-05-10 11:46
    关注

    I've had a similar problem before, I don't know if it will work for you but you can try addslashes() like this:

    $fields = [
        'phone' => "+48667421797",
        'msg'   => "Great app! Thank you!",
    ];
    
    $data = addslashes(json_encode($fields)); 
    // outputs {\"phone\":\"+48667421797\",\"msg\":\"Great app! Thank you!\"}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料