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     }

個人記錄一下哈


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM