很多朋友在使用google GeolocationAPI 接口測試基站定位,測試時需要往接口http://www.google.com/loc/json送出json格式的資料,json格式參數比較多,在IDE裡測試起來也比較麻煩,有時因為一個文法錯誤不得不排查很長時間。
這裡ant 推薦一個比較簡單的方法來測試json資料格式是否正确:使用curl測試。
curl 是一個利用URL文法在指令行方式下工作的檔案傳輸工具。使用curl來送出http GET/POST資料很是友善。curl是Unix/Linux下常用的工具,也有windows版本 。
GeolocationAPI 的詳細文法這裡就不介紹了。
例如我們想通過http://www.google.com/loc/json查詢LAC:14556 ,CELLID:36525 的基站位置。根據GeolocationAPI 裡提到的文法,送出的資料應該是這樣的格式:
{
"version": "1.1.0" ,
"host": "maps.google.com",
"access_token": "2:k7j3G6LaL6u_lafw:4iXOeOpTh1glSXe",
"home_mobile_country_code": 460,
"home_mobile_network_code":0,
"address_language": "zh_CN",
"radio_type": "gsm",
"request_address": true ,
"cell_towers":[
{
"cell_id":36526,
"location_area_code":14556,
"mobile_country_code":460,
"mobile_network_code":0,
"timing_advance":5555
}
]
}
下面我們通過curl測試該格式是否正确。
指令格式: curl -d ‘post的資料’ http://www.google.com/loc/json
這裡隻需要用到curl的-d參數,-d後面跟的是post的資料内容
在指令行下輸入” curl -d ‘ “後回車,粘貼上面的json格式資料回車,再輸入” ‘ http://www.google.com/loc/json”回車,就可以看到google的傳回結果了。
通過curl可以友善的測試各種json參數組合。
更具以上接口說明,我寫了以下可用代碼
<?php
function curl_post($url, $vars, $second=30)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$vars = '{
"version": "1.1.0" ,
"host": "maps.google.com",
"access_token": "2:k7j3G6LaL6u_lafw:4iXOeOpTh1glSXe",
"home_mobile_country_code": 460,
"home_mobile_network_code":0,
"address_language": "zh_CN",
"radio_type": "gsm",
"request_address": true ,
"cell_towers":[
{
"cell_id":36526,
"location_area_code":14556,
"mobile_country_code":460,
"mobile_network_code":0,
"timing_advance":5555
}
]
}';
$rdata = curl_post('http://www.google.com/loc/json',$vars);
$r_ary = (array) json_decode($rdata);
print_r($r_ary['location']);
?>