平时的项目开发中,都会用到数据请求,一般都会用到Curl 和 stream流的方式发送http请求。
一、CURL
// curl请求 HTTPS 请求,编码必须为 UTF-8 public function curl_post($url, $param, $post_file = false) { $oCurl = curl_init(); if (stripos($url, "https://") !== FALSE) { curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } $headers = array('content-type: application/x-www-form-urlencoded;charset=utf-8'); curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers); curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($oCurl, CURLOPT_POST, true); curl_setopt($oCurl, CURLOPT_POSTFIELDS, json_encode($param)); $sContent = curl_exec($oCurl); $aStatus = curl_getinfo($oCurl); curl_close($oCurl); if (intval($aStatus["http_code"]) == 200) { return $sContent; } else { return false; } }
二、stream数据流
public function post2($url, $rawData){ ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); //伪造 user_agent 防止请求报错 $opts = array( 'http' => array( 'method' => "POST", 'header' => "Content-type: application/json\r\nContent-length:" . strlen($rawData) . "\r\n", 'content' => $rawData, ),"ssl" => [ "verify_peer"=>false, "verify_peer_name"=>false, ] ); $context = stream_context_create($opts); $content = file_get_contents($url, false, $context); return $content; }