接收别人接口的方法---httpreques(推荐学习:php编程从入门到精通)
/** * curl请求 * @param $url 请求url地址 * @param $method 请求方法 get post * @param null $postfields post数据数组 * @param array $headers 请求header信息 * @param bool|false $debug 调试开启 默认false * @return mixed */function httprequest($url, $method, $postfields = null, $headers = array(), $debug = false) { $method = strtoupper($method); $ci = curl_init(); /* curl settings */ curl_setopt($ci, curlopt_http_version, curl_http_version_1_0); curl_setopt($ci, curlopt_useragent, "mozilla/5.0 (windows nt 6.2; wow64; rv:34.0) gecko/20100101 firefox/34.0"); curl_setopt($ci, curlopt_connecttimeout, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */ curl_setopt($ci, curlopt_timeout, 7); /* 设置curl允许执行的最长秒数 */ curl_setopt($ci, curlopt_returntransfer, true); switch ($method) { case "post": curl_setopt($ci, curlopt_post, true); if (!empty($postfields)) { $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields; curl_setopt($ci, curlopt_postfields, $tmpdatastr); } break; default: curl_setopt($ci, curlopt_customrequest, $method); /* //设置请求方式 */ break; } $ssl = preg_match('/^https:\/\//i',$url) ? true : false; curl_setopt($ci, curlopt_url, $url); if($ssl){ curl_setopt($ci, curlopt_ssl_verifypeer, false); // https请求 不验证证书和hosts curl_setopt($ci, curlopt_ssl_verifyhost, false); // 不从证书中检查ssl加密算法是否存在 } //curl_setopt($ci, curlopt_header, true); /*启用时会将头文件的信息作为数据流输出*/ curl_setopt($ci, curlopt_followlocation, 1); curl_setopt($ci, curlopt_maxredirs, 2);/*指定最多的http重定向的数量,这个选项是和curlopt_followlocation一起使用的*/ curl_setopt($ci, curlopt_httpheader, $headers); curl_setopt($ci, curlinfo_header_out, true); /*curl_setopt($ci, curlopt_cookie, $cookiestr); * *cookie带过去** */ $response = curl_exec($ci); $requestinfo = curl_getinfo($ci); $http_code = curl_getinfo($ci, curlinfo_http_code); if ($debug) { echo "=====post data======\r\n"; var_dump($postfields); echo "=====info===== \r\n"; print_r($requestinfo); echo "=====response=====\r\n"; print_r($response); } curl_close($ci); return $response; //return array($http_code, $response,$requestinfo);}
实例
$url = 'http://linmin.lalal.com/hello/index.php?s=/api/api/index'; $api_key = 'f8e267731fd852ae841d841903559ef6'; $data = [ 'key' => $api_key, 'type' => 'get-admin-user-list', 'data' => [ 'page' => 1, //* 'length' => 10, //(不传默认10条) ], ]; $res =httprequest($url,'post',$data); $json_array = json_decode($res,true); $data=$json_array['data']['admin_user_list']; $this->assign('json_array',$data); $this->display();
以上就是如何调用别人给的php接口的详细内容。