thinkphp5.0 CURL用post请求接口数据

 1     //测试 请求接口
 2     public function  index(){
 3         $arr = array('a'=>'555','b'=>56454564);
 4         $data=$this->post_json_data('http://www.test.com/public/index/api/postTest',json_encode($arr));
 5         dump(json_decode($data['result'],true));
 6     }
 7 
 8     //测试 接口
 9     public function postTest(){
10          //显示获得的数据
11         if($this->request->isPost()){
12             $arr = array('a'=>'666666','b'=>999999);
13             return json_encode($arr);
14         }
15 
16     }
17     /*
18      * post 发送JSON 格式数据
19      * @param $url string URL
20      * @param $data_string string 请求的具体内容
21      * @return array
22      *      code 状态码
23      *      result 返回结果
24      */
25     function post_json_data($url, $data_string) {
26         //初始化
27         $ch = curl_init();
28         //设置post方式提交
29         curl_setopt($ch, CURLOPT_POST, 1);
30         //设置抓取的url
31         curl_setopt($ch, CURLOPT_URL, $url);
32         //设置post数据
33         curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
34         //设置头文件的信息作为数据流输出
35         curl_setopt($ch, CURLOPT_HTTPHEADER, array(
36                 'Content-Type: application/json; charset=utf-8',
37                 'Content-Length: ' . strlen($data_string))
38         );
39         ob_start();
40          //执行命令
41         curl_exec($ch);
42         $return_content = ob_get_contents();
43         ob_end_clean();
44         $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
45         return array('code'=>$return_code, 'result'=>$return_content);
46     }

个人记录一下哈

原文地址:https://www.cnblogs.com/zgbcode/p/9963994.html