php封裝curl的post和get類

來源:互聯網
上載者:User
<pre name="code" class="php"><?class curl{/** * get方法 * * @param string 介面地址 * @param string endpoint  * @param string model名 * @param string 方法名 * @param array 參數 * @return json */    static public function sendByGet($host,$data){$fields_string = '';if(!empty($data)){ksort($data);$fuhao = '';foreach($data as $k=>$v){$fields_string .=$fuhao.$v;$fuhao = '/';}}        if(!empty($fields_string)){            $url = $host.'/'.$fields_string;        } else {            $url = $host;        }$ch = curl_init() ;curl_setopt($ch, CURLOPT_URL,$url) ;curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_TIMEOUT, 5);        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);$str = curl_exec($ch);        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE );        curl_close($ch);   if ($status == 200) {return $str;} else {return false;}}    /**     * post方法     *     * @param string 介面地址     * @param array 參數     * @return json     */public function sendByPost($url,$data,$cookie=''){$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);if($cookie){curl_setopt($ch, CURLOPT_COOKIE, $cookie);}curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120 );curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);curl_setopt($ch, CURLOPT_POSTFIELDS, $data );$str = curl_exec($ch);if (curl_errno($ch)) {     $error = "Curl error: " . curl_error($ch)."\n時間:".date('Y-m-d H:i:s',time())."\r\n"; file_put_contents('curl_post_error.txt',$error,FILE_APPEND);}curl_close($ch) ;return $str;}}

當擷取https協議請求時需加上

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.