php Post请求
在php调用一个 Post请求接口
/** * PHP发送Json对象数据 * * @param $url 请求url * @param $jsonStr 发送的json字符串 charset=utf-8 * @return array */ function http_post_json($url, $jsonStr) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json;charset=utf-8', 'Content-Length: ' . strlen($jsonStr) ) ); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return array($httpCode, $response); } /** * PHP发送 Post请求 * * @param $url 请求url * @param $jsonStr * @return array */ function http_post($url, $jsonStr) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST,true); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return array($httpCode, $response); }
调用方法
一、JSON方式请求
//请求 接口 -------------------------------------------------------------------- $url = "http://111.110.196.159:11585/cdrl/api/mobile/ABCHouse.act"; //$jsonStr = json_encode(array('tel' => '13478956906', 'companyNo' => '040000')); $jsonStr = json_encode(array('tel' => $Tel, 'companyNo' => $CompanyNo )); list($returnCode, $returnContent) = http_post_json($url, $jsonStr); WriteLog("$LogParm 请求接口 返回码:".$returnCode." 参数:" .$jsonStr." 返回值:" .$returnContent ); //请求失败---- 返回码 不为200 则 认为 请求失败---------- if($returnCode!="200"){ $arr_result['action']='Action_Hangup'; WriteLog("$LogParm ". "请求接口失败 " . $returnCode ." $url $jsonStr " ); WriteLog("$LogParm 返回值 " .json_encode($arr_result)); echo json_encode($arr_result ); exit(0); } //分析 returnContent $obj_returnContent= json_decode($returnContent);//JSON转为object对象 if($obj_returnContent->message=="find the data"){ $arr_data = object_array($obj_returnContent->data);//JSON转为数组 $data_count = count($arr_data);//数组的长度 //WriteLog("是否 returnContent 为 ". $arr_data[0]['address'] ." " .$data_count ." " ); for($i=0;$i<$data_count;$i++){ $num=$i+1; $play_content=$play_content .'。'.$num .",". $arr_data[$i]['address']; } }
二、Post方式请求
$url = "http://111.111.24.15/lyyl/callcenter/api/external/getAbbbbt.act"; $jsonStr = array('callid' => $Tel );
list($returnCode, $returnContent) = http_post($url, json_encode($jsonStr));
WriteLog("$LogParm 请求 接口 返回码:".$returnCode." 返回值:" .$returnContent." 参数:" .json_encode($jsonStr) );