curl post請求封裝

 2 /* 
 3 POST /servlet/ICBCCMPAPIReqServlet?userID=jyi.y.1001&PackageID=201807311347539185&SendTime=20180731134755 HTTP/1.1  4 Host: 127.0.0.1:7070  5 Accept:*  6 Content-Type:application/x-www-form-urlencoded  7 Content-Length: 4211  8 Expect: 100-continue  9 
10  */
11 
12 /* 
13 HTTP/1.1 100 Continue 14  */
15  
16 /** 17  * * curlPost請求 18  * @param string $url 請求的url 19  * @param array $dataArr 發送的數據 20  * @param string $dataType 發送數據類型 21  * @param array $headerArr 請求頭 22  * @param int $timeout 超時時間 23  * @author:songjm 24  * @date:2018.7.31 25  * @return array 26  */
27 function curlPost($url, $dataArr, $dataType = 'arr', $headerArr = array(), $timeout = 3) 28 { 29     $headerArr[] = 'Expect:'
30     //防止libcurl發送大於1024字節數據時啓用HTTP/1.1的Expect:100-continue特性
31     $ch = curl_init(); //初始化curl
32     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而不直接輸出
33     curl_setopt($ch, CURLOPT_URL, $url); //設置請求的url
34     curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); 35     curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 36     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不驗證對等證書
37     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //不檢查服務器SSL證書
38 
39     $dataType = strtolower($dataType); 40     if ($dataType == 'json') 41  { 42         $data = json_encode($dataArr); 43  } 44     elseif ($dataType == 'ser') 45  { 46         $data = serialize($dataArr); 47  } 48     elseif ($dataType == 'raw') 49  { 50         $data = $dataArr; 51  } 52     else
53  { 54         $data = http_build_query($dataArr); 55  } 56     curl_setopt($ch, CURLOPT_POST, true); //設置爲POST請求
57     curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //設置POST的請求數據(字符串或數組)
58 
59     $response = curl_exec($ch); 60     if ($error = curl_error($ch)) 61  { 62         $bkArr =  array( 63             'code' => 0,
64             'msg' => $error,
65  ); 66  } 67     else
68  { 69         $bkArr =  array( 70             'code' => 1,
71             'msg' => 'ok',
72             'resp' => $response,
73  ); 74  } 75 
76     curl_close($ch); // 關閉 cURL 釋放資源
77 
78     return $bkArr; 79 }
相關文章
相關標籤/搜索