PHP使用curl模拟浏览器请求接口

php开发中接口是不可避免的一个环节,那么关于该问题中我们又会遇到各类千奇百怪的问题。关于这些问题我们要有自己的解决方案,本文已现有接口需要模拟浏览器请求数据为例:

如假设该接口:

http://****.com/index/index
function curlGetData() {
$config = array();
$url = 'http://****.com/index/index';
$arr = array(
'file'=>'',
'postname'=>'',
'post' => false,
'referer' => $url,
'cookie' => '',
'useragent' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)',
'connectout'=>3,
'timeout' => 10,
'return' => true,
'proxy' => '',
'userpwd' => '',
'nobody' => false,
'header'=>array(),
'gzip'=>true,
'ssl'=>false,
'isupfile'=>false,
'returnheader'=>false);
$arr = array_merge($arr, $config);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//参数为1表示传输数据,为0表示直接输出显示。
// curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $arr['connectout']);
curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);
// proxy
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 跳过检查
// //参数为0表示不带头文件,为1表示带头文件
// curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'content-type: application/json; charset=utf-8',
));
$output = curl_exec($ch);
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$newDataR['data'] = json_decode($output,true);
$newDataR['code'] = $return_code;
// return $output;
return $newDataR;
}

反馈数据类型:

{
code:200,
data:[]
}

若有需要直接拿代码测试吧,原理和一些说明我就不细说了。

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!