// 单个请求
public function curlSingle($url = "", $data) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5); curl_setopt($ch,CURLOPT_TIMEOUT,5); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8")); $output = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return json_decode($output, true); }
/** * 一次请求多个几接口 * @author mijunzhu 2016-01-02 * @param $arData array( array('url'=>地址,'data'=>array()) ) * @return string json串 */ function curlMulti( $arData ) { $mh = curl_multi_init(); foreach ($arData as $i => $vData) { $conn[$i] = curl_init($vData['url']); curl_setopt($conn[$i], CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($conn[$i], CURLOPT_POSTFIELDS, json_encode($vData['data'])); curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER,true); curl_setopt($conn[$i], CURLOPT_CONNECTTIMEOUT,10); curl_setopt($conn[$i], CURLOPT_TIMEOUT,10); curl_setopt($conn[$i], CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8")); curl_multi_add_handle($mh,$conn[$i]); } $active = null; do { $mrc = curl_multi_exec($mh,$active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active and $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } foreach ($arData as $i => $vData) { $res[$i] = json_decode( curl_multi_getcontent($conn[$i]) , true); curl_close($conn[$i]); } return json_encode( $res ); }