php通过CURL模拟post提交请求
1 <?php 2 header("Content-type:text/html;charset=utf-8"); 3 4 class Test{ 5 6 public function request_post($url = '', $param = '',$headers = array()){ 7 if (empty($url) || empty($param) || empty($headers)) { 8 return false; 9 } 10 11 $postUrl = $url; 12 $curlPost = $param; 13 $curlHeader = $headers; 14 $ch = curl_init();//初始化curl 15 curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页 16 curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeader);//设置header 17 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 18 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 19 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); 20 $data = curl_exec($ch);//运行curl 21 curl_close($ch); 22 23 return $data; 24 } 25 26 public function testAction(){ 27 $url = 'http://web.zhimabot.com:8080/parsor9/robot'; 28 $post_data['app_id'] = '51'; 29 $post_data['client_id'] = '123456'; 30 $post_data['session_id'] = '1528883027691'; 31 $post_data['intent_update'] = ''; 32 $post_data['query'] = '播放刘德华的忘情水'; 33 34 $headers = array(); 35 array_push($headers, "Content-Type: application/json; charset=utf-8","Accept: application/json"); 36 $post_data = json_encode($post_data,JSON_UNESCAPED_UNICODE); 37 38 $res = $this->request_post($url, $post_data,$headers); 39 return $res; 40 } 41 42 } 43 44 45 function fn(){ 46 $action = new Test(); 47 $result = $action->testAction(); 48 var_dump($result); 49 } 50 51 fn(); 52 53 ?>