本文从http://m.weather.com.cn/获取天气信息。
接口已经停用了,http://m.weather.com.cn/data/101090507.html,需要使用新接口。
得到数据
{"weatherinfo":{"city":"迁西","cityid":"101090507","temp1":"16℃","temp2":"1℃","weather":"多云","img1":"d1.gif","img2":"n1.gif","ptime":"08:00"}}
String src ="http://www.weather.com.cn/data/cityinfo/101090507.html";
String getJson(String src) {
try {
URL url = new URL(src);
int lineIndex=0;
HttpURLConnection httpConnect = (HttpURLConnection) url.openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(httpConnect.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line ="";
String jsonStr = "";
while((line = bufferedReader.readLine())!=null){
lineIndex++;
jsonStr += line;
}
Log.e(TAG, jsonStr);
return jsonStr;
} catch (IOException e){
e.printStackTrace();
}
return "";
}
此段代码的返回值,即是json格式的天气信息。
String getWeatherInfo(String json){
String weatherInfo ="";
try{
String filed ="";
JSONObject obj = new JSONObject(json);
filed = obj.getString("weatherinfo");
JSONObject objsub=new JSONObject(filed);
weatherInfo+="深圳 ,";
weatherInfo += objsub.getString("temp1") + "--";
weatherInfo += objsub.getString("temp2") + ", ";
weatherInfo += objsub.get("weather");
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG,weatherInfo);
return weatherInfo;
}