/**
* http测试
* 注:php版本5.2以上才支持curl_ipresolve_v4
* @param $url 网站域名
* @param $type 网站访问协议
* @param $ipresolve 解析方式
*/
public function web_http($url,$type,$ipresolve) {
//设置header头
$header[] = "accept: application/json";
$header[] = "accept-encoding: gzip";
$httptype = function_exists('curl_init');
if (!$httptype) {
$html = file_get_contents($url);
} else {
$ch = curl_init();
curl_setopt($ch, curlopt_url, $url);
//输出头信息
curl_setopt($ch, curlopt_header, 1);
//递归访问location跳转的链接,直到返回200ok
curl_setopt($ch, curlopt_followlocation, 1);
//不对html中的body部分进行输出
curl_setopt($ch, curlopt_nobody, 1);
//将结果以文件流的方式返回,不是直接输出
curl_setopt($ch, curlopt_returntransfer, 1);
//以ipv4/ipv6的方式访问
if($ipresolve=='ipv6') {
curl_setopt($ch,curlopt_ipresolve,curl_ipresolve_v6);
}else{
curl_setopt($ch,curlopt_ipresolve,curl_ipresolve_v4);
}
//添加http header头采用压缩和get方式请求
curl_setopt( $ch, curlopt_httpheader, $header );
curl_setopt($ch,curlopt_encoding , "gzip");
curl_setopt($ch, curlopt_customrequest, 'get');
//清除dns缓存
curl_setopt($ch,curlopt_dns_cache_timeout,0);
//设置连接超时时间
curl_setopt($ch,curlopt_connecttimeout,15);
//设置访问超时
curl_setopt($ch,curlopt_timeout,50);
//设置user-agent
curl_setopt($ch,curlopt_useragent,'mozilla/5.0 (windows nt 6.1) applewebkit/536.11 (khtml, like gecko) chrome/20.0.1132.47 safari/536.11');
if($type=="https") {
//不对认证证书来源的检查
curl_setopt($ch, curlopt_ssl_verifypeer, false);
//从证书中检查ssl加密算法是否存在
curl_setopt($ch, curlopt_ssl_verifyhost, true);
}
//执行curl操作
$html = curl_exec($ch);
//获取一个curl连接资源句柄的信息(获取最后一次传输的相关信息)
$info = curl_getinfo($ch);
curl_close($ch);
}
return $info;
}
以上为一个基本curl访问的方法,由于这里需要通过使用ipv6的方式,所以加了相应的选项,相信大家能看的明白,平时经常用到的选项上面都有出现,大家根据需要取舍。
状态码提示405/method not allowed表示不支持请求的方法,这个错误并不常见。
导致这个错误是要是由于curl默认是采用post方式进行提交访问的,post方式在此类域名下是没有权限的,比如在测试www.amazon.cn的时候就出现了这类问题,而修改为get的方式,并且增加了header头后,即可正常访问,个人推测,或许是亚马逊那边基本上都是采用get的方式,才会被认为是人为的点击,对post做了相应屏蔽。
对此增加了如下代码:
//设置header头 $header[] = "accept: application/json"; $header[] = "accept-encoding: gzip"; //添加http header头采用压缩和get方式请求 curl_setopt( $ch, curlopt_httpheader, $header ); curl_setopt($ch,curlopt_encoding , "gzip"); curl_setopt($ch, curlopt_customrequest, 'get');
命令行的形式为:
curl -v www.amazon.cn
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!