发送GET请求
1 $url = "http://xxx.xxx.xxx.xxx"; 2 $get_data = array ("output" => "json", 3 "a" => "xxx", 4 "b" => "xxx", 5 "ak" => $ak, 6 "origins" => $origins, 7 "destinations" => $destinations 8 ); 9 10 foreach ($get_data as $k => $v) { 11 $data[] = $k.'='.$v; 12 } 13 $p_str = implode('&', $data); 14 $url .= '?'.$p_str; 15 16 $ch = curl_init(); 17 18 curl_setopt($ch, CURLOPT_URL, $url); 19 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 20 21 $output = curl_exec($ch); 22 curl_close($ch); 23 24 $output_array = json_decode($output,true);
步骤:
1、先拼出url
2、使用curl一系列函数
3、得到结果之后使用json_decode函数进行json的解析,可以直接通过k-v的形式拿到值
发送POST请求
1 $url = "xxx.xxx.xxx.xxx"; 2 3 $pieces1 = explode(",", $origins); 4 $pieces2 = explode(",", $destinations); 5 6 $params = json_encode(array 7 ( 8 'xxx_list' => array 9 ( 10 array( 11 'xx1' => array( 12 'a' => intval($pieces1[0]), 13 'b' => intval($pieces1[1]) 14 ), 15 'xx2' => array( 16 'c' => intval($pieces2[0]), 17 'd' => intval($pieces2[1]) 18 ), 19 'xx3' => array( 20 'xx11' => $data['xx11'], 21 'xx22' => $data['xx22'] 22 ) 23 ) 24 ), 25 'xxx_type' => 0 26 ) 27 ); 28 29 30 $ch = curl_init(); 31 32 curl_setopt($ch, CURLOPT_URL, $url); 33 curl_setopt($ch, CURLOPT_HTTPHEADER, array( 34 'Content-Type: application/json', 35 'Content-Length: ' . strlen($params) 36 )); 37 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 38 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 39 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 40 curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 41 42 $res = curl_exec($ch); 43 curl_close($ch);
步骤:
1、构造params
2、使用curl一系列函数
curl中CURLOPT_POSTFIELDS参数就是设置body的内容,这里设置为post提交是用CURLOPT_CUSTOMREQUEST而不是CURLOPT_POST,根据官网的说明:
CURLOPT_POST:启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
因为是要发送json格式,所以不能用这个。
本文参考自:
http://www.01happy.com/php-send-post-request-body-is-json/
http://www.01happy.com/php-post-request-get-json-param/