中国国家气象局天气预报接口总共提供了三个:
//实时天气预报
http://www.weather.com.cn/data/sk/101190101.html
//当天基础天气接口
http://www.weather.com.cn/data/cityinfo/101190101.html
//六天预报
http://m.weather.com.cn/data/101190101.html
注:上面接口2014.3.4日已不再更新。换成:http://m.weather.com.cn/atad/101190101.html。
下面利用这个接口获取南京天气信息:
代码如下:
public class MainActivity extends Activity {
Button btn=null;
String strUrlBase="http://m.weather.com.cn/atad/101190101.html";
int[] tvs={R.id.city,R.id.temp1,R.id.wind1,R.id.weather};
Handler handler=new Handler(){
public void handleMessage(Message msg) {
String strWeather=msg.getData().getString("strWeather");
String[] weathers=strWeather.split(",");
for(int i=0;i<weathers.length;i++){
String str=weathers[i];
Log.i("str", str);
TextView tv=(TextView) findViewById(tvs[i]);
tv.setText(str);
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
btn=(Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
URL url=new URL(strUrlBase);
InputStream is=url.openStream();
String strWeather=parseWeather(is);
Message msg=new Message();
Bundle bundle=new Bundle();
bundle.putString("strWeather", strWeather);
msg.setData(bundle);
handler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
private String parseWeather(InputStream is) {
String str=Utils.convertStreamToString(is);
Log.i("str",str);
try {
JSONObject json=new JSONObject(str);
JSONObject weatherinfo=json.getJSONObject("weatherinfo");
String city=weatherinfo.getString("city");
String temp1=weatherinfo.getString("temp1");
String wind1=weatherinfo.getString("wind1");
String weather=weatherinfo.getString("weather1");
Log.i("city",city );
Log.i("temp1", temp1);
Log.i("temp2",wind1 );
Log.i("weather",weather );
str=city+","+temp1+","+wind1+","+weather;
} catch (JSONException e) {
e.printStackTrace();
}
return str;
}
}
-----------------------
public class Utils {
public static String convertStreamToString(InputStream is) {
BufferedReader br= new BufferedReader(new InputStreamReader(is),10*1024);
StringBuilder sb=new StringBuilder();
String line=null;
try {
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
运行效果如下: