赞
踩
1、HTTP 调用接口(curl方法)
注解:$url:接口地址,$params:接口参数(数组),$method:传递方式,$header:访问方式,$timeout:设置cURL允许执行的最长秒数
例子:
我们可以通过PHP的CURL函数的CURLOPT_HTTPHEADER来配置设置host访问。
$header = array("Host: act.qzone.qq.com");
- public function http($url, $params, $method = 'GET', $header = array(), $timeout = 5){
- // POST 提交方式的传入 $set_params 必须是字符串形式
- $opts = array(
- CURLOPT_TIMEOUT => $timeout,
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_HTTPHEADER => $header
- );
- /* 根据请求类型设置特定参数 */
- switch (strtoupper($method)) {
- case 'GET':
- $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
- break;
- case 'POST':
- // $params = json_encode($params,true);
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_POST] = 1;
- $opts[CURLOPT_POSTFIELDS] = $params;
- break;
- case 'DELETE':
- $params = json_encode($params,true);
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_HTTPHEADER] = array("X-HTTP-Method-Override: DELETE");
- $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
- $opts[CURLOPT_POSTFIELDS] = $params;
- break;
- case 'PUT':
- $params = json_encode($params,true);
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_POST] = 0;
- $opts[CURLOPT_CUSTOMREQUEST] = 'PUT';
- $opts[CURLOPT_POSTFIELDS] = $params;
- break;
- case 'PATCH':
- $params = json_encode($params,true);
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_POST] = 0;
- $opts[CURLOPT_CUSTOMREQUEST] = 'PATCH';
- $opts[CURLOPT_POSTFIELDS] = $params;
- break;
- default:
- throw new Exception('不支持的请求方式!');
- }
- /* 初始化并执行curl请求 */
- $ch = curl_init();
- curl_setopt_array($ch, $opts);
- $data = curl_exec($ch);
- $error = curl_error($ch);
- return $data;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。