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!\"}
    
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大