package GoogleJson; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONException; import org.json.JSONObject; public class LocationUtil { private JSONObject getAreaObj(LocationUtil test,int cellID){ URL url = null; HttpURLConnection conn = null; JSONObject result = null; try { url = new URL("http://www.google.com/loc/json"); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); String json = test.getJson(cellID); // System.out.println(json); conn.getOutputStream().write(json.getBytes()); conn.getOutputStream().flush(); conn.getOutputStream().close(); int responseCode = conn.getResponseCode(); System.out.println("code :" + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn .getInputStream())); String inputLine; inputLine = in.readLine(); in.close(); result = new JSONObject(inputLine); // location = result.getJSONObject("location"); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } return result; } private String getJson(int cellID){ String json = "{ " + "\"version\": \"1.1.0\", " + "\"host\": \"maps.google.com\", " // + + "\"home_mobile_country_code\": 460, " + "\"home_mobile_network_code\": 00, " + "\"radio_type\": \"gsm\", " + "\"carrier\": \"Vodafone\", " + "\"request_address\": true, " + "\"address_language\": \"zh_CN\", " + "\"cell_towers\": [ " + "{ " + "\"cell_id\": "+cellID+", " + "\"location_area_code\": 20516, " + "\"mobile_country_code\": 460, " + "\"mobile_network_code\": 00, " + "\"age\": 0, " + "\"signal_strength\": -60, " + "\"timing_advance\": 5555 " + "}" + "]" + "}"; return json; } public static void main(String args[]) throws JSONException { int cellID = 4913; LocationUtil test = new LocationUtil(); // 解析結果 JSONObject result = test.getAreaObj(test, cellID); JSONObject location = result.getJSONObject("location"); JSONObject address = location.getJSONObject("address"); double latitude = location.getDouble("latitude"); double longitude = location.getDouble("longitude"); System.out.println("longitude = " + longitude); System.out.println("latitude = " + latitude); System.out.println(address.getString("country") + address.getString("region") + address.getString("city") + address.getString("street")); } }
這個例子裏用的是org.json.jar包,今天把這小例子放到項目中發現項目的json包是json-lib.,此時更換jar包對項目影響比較大,改下代碼:java
首先修改import net.sf.json.*;git
再修改result = new JSONObject(inputLine) 爲 result = JSONObject.fromObject(inputLine)。json
這樣就不用更新項目裏的jar包了。google