Obtain and parse important meteorological station data
The project uses json parsing and writes a demo to obtain json data from the Central Meteorological Observatory and parse the data locally. Record it.
Online data retrieval logic:
Private void loadData () {Log. d ("wlj", "loadData >>>>"); HttpParams params = new BasicHttpParams (); // set connection timeout or response timeout HttpConnectionParams. setConnectionTimeout (params, 5000); HttpConnectionParams. setSoTimeout (params, 5000); HttpClient client = new DefaultHttpClient (params); HttpGet request = new HttpGet ("http://m.weather.com.cn/data/101280601.html"); HttpResponse response; InputStream is; try {response = client.exe cute (request); if (HttpStatus. SC _ OK = response. getStatusLine (). getStatusCode () {is = response. getEntity (). getContent (); json (is);} else {Log. d ("wlj", "failed to get network data... ") ;}} catch (ClientProtocolException e) {Log. d ("wlj", "ClientProtocolException... "); e. printStackTrace ();} catch (IOException e) {Log. d ("wlj", "IOException... "); e. printStackTrace ();} finally {client. getConnectionManager (). shutdown ();}}
Json data parsing logic:
private void json(InputStream is){JsonReader reader = null;try {reader = new JsonReader(new InputStreamReader(is, "UTF-8"));reader.beginObject();if(reader.nextName().equalsIgnoreCase("weatherinfo")){reader.beginObject();while(reader.hasNext()){String name = reader.nextName();if(name.equalsIgnoreCase("city_en")){Log.d("wlj", "city is " + reader.nextString());}else if(name.equalsIgnoreCase("temp5")){Log.d("wlj", "temp5 is " + reader.nextString());}else if(name.equalsIgnoreCase("index_d")){Log.d("wlj", "index_d is " + reader.nextString());}else{reader.skipValue();}}reader.endObject();}reader.endObject();} catch (IOException e) {Log.d("wlj", "parse reader IOException ... ");e.printStackTrace();}finally{try {if(is != null) is.close();if(reader != null) reader.close();} catch (IOException e) {Log.d("wlj", "close reader IOException ... ");e.printStackTrace();}}}
From the json parsing logic, we can see that the json parsing logic is highly correlated with the data format returned by the server, which must be one-to-one matched according to the format defined by the server.