在请求json数据时,浏览器可以打开,查看状态码也是200,但在请求的页面却报302错误。这是因为请求做了302跳转,因此需要判断是否有302跳转。
若请求url已改变且设置了自动跳转,可通过设置 CURLOPT_FOLLOWLOCATION 参数实现自动请求跳转链接。若要手动判断是否跳转,可通过 curl_getinfo($ch) 方法获取具体请求信息,其中包括要跳转路径。
实例:
<?php $url = 'http://dvy.com.cn/'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //若给定url自动跳转到新的url,有了下面参数可自动获取新url内容:302跳转 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //设置cURL允许执行的最长秒数。 curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'); curl_setopt($ch, CURLOPT_REFERER, $url); curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate'); $content = curl_exec($ch); //获取请求返回码,请求成功返回200 $code = curl_getinfo($ch,CURLINFO_HTTP_CODE); echo $code . "\n\n"; //获取一个cURL连接资源句柄的信息。 //$headers 中包含跳转的url路径 $headers = curl_getinfo($ch); var_dump($headers); // $content 为url请求内容 //echo "\n\n" . $content . "\n";
curl_getinfo($ch) 返回信息如下:
array ( 'url' => 'http://dvy.com.cn/', 'content_type' => 'text/html', 'http_code' => 301, 'header_size' => 352, 'request_size' => 206, 'filetime' => -1, 'ssl_verify_result' => 0, 'redirect_count' => 0, 'total_time' => 0.13020600000000004, 'namelookup_time' => 0.021582, 'connect_time' => 0.053791999999999951, 'pretransfer_time' => 0.053817000000000004, 'size_upload' => 0.0, 'size_download' => 182.0, 'speed_download' => 1397.0, 'speed_upload' => 0.0, 'download_content_length' => 182.0, 'upload_content_length' => 0.0, 'starttransfer_time' => 0.13016799999999995, 'redirect_time' => 0.0, 'redirect_url' => 'http://dvy.com.cn/', 'primary_ip' => '8.8.8.8', 'certinfo' => array ( ), )