【问题标题】:How can I convert json request to php [duplicate]如何将json请求转换为php [重复]
【发布时间】:2018-06-06 06:56:20
【问题描述】:

我想在 PHP 中发布以下 JSON HTTP API 请求

    curl -d '{"text":"Hello, #param#.","port":[2],"param":
    [{"number":"123456","text_param ":["John"],"user_id":1}]}’-u 
    myusername:mypassword –H "Content-Type: application/json"  
    http://accbd.com/api/send_req 

【问题讨论】:

  • 要从 PHP 发送 http 请求,您需要使用 curl
  • 如何使用 -u myusername:mypassword

标签: php json


【解决方案1】:

你可以试试下面的代码

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://accbd.com/api/send_req');
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type' => 'application/json'));
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_USERPWD, "myusername:mypassword");  
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, '{"text":"Hello, #param#.","port":[2],"param":[{"number":"123456","text_param ":["John"],"user_id":1}]}');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);


$data = curl_exec($curl);
curl_close($curl);
echo $data;exit;

【讨论】:

  • 得到错误 Pragma: no-cache Cache-Control: no-cache Content-Type: application/json
  • 你遇到了什么错误?
  • HTTP/1.1 400 页面未找到服务器:Web 服务器/2.1.0 日期:2017 年 12 月 23 日星期六 10:07:17 编译指示:无缓存缓存控制:无缓存内容类型:应用程序/json
  • curl_setopt($curl, CURLOPT_URL, '192.168.11.1:5851/api/send_sms'); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type' => 'application/json')); curl_setopt($curl, CURLOPT_HEADER, 1); curl_setopt($curl, CURLOPT_USERPWD, "ali:reza345934"); curl_setopt($curl, CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, '{"text":"Hello, #param#.","port":[2,3],"param":[{"number":"01784787670","text_param": ["John"],"user_id":1},{"number":"01784787670", "text_param":["Sam"],"user_id":2}]}'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
  • 请为 CURLOPT_URL 选项使用正确的 URL。 192.168.11.1:5851/api/send_sms 似乎不起作用。
猜你喜欢
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 2019-07-22
  • 2023-03-26
  • 1970-01-01
  • 2017-04-12
相关资源
最近更新 更多