获取网络上的天气数据
- 有一个天气预报发布网站
天气预报系统最重要的是获得有效、准确的天气信息,要想获取实时的天气信息,需要访问专门提供天气信息的网站把网站返回的信息解析出想要的信息并显示在手机上。使用中华万年历得到的接口(JSON):
http://wthrcdn.etouch.cn/weather_mini?city=北京 (城市名称)
可以直接通过城市名字获得天气数据,json数据,实现起来方便而且数据准确,天气信息和中国天气网(www.weather.com.cn)一致。
private String getUrl(String cityname){
return "http://wthrcdn.etouch.cn/weather_mini?city="+cityname;
}
- 借助HttpUrlConnection(java.net.HttpUrlConnection),获取Url网页上的数据;
public class XHttpConnection {
private IHttpConnection iHttpConnection;
public XHttpConnection(IHttpConnection iHttpConnection){
this.iHttpConnection = iHttpConnection;
}
public void get(final String path){
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(5 * 1000);
connection.connect();
int response = connection.getResponseCode();
if(response == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
String html = dealResponseResult(inputStream);
Message msg = new Message();
msg.what = 1;
msg.obj = html;
mHandler.sendMessage(msg);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case 1:
iHttpConnection.resultGet(msg.obj.toString().trim());
break;
}
return false;
}
}
- 存储处理结果
private String dealResponseResult(InputStream inputStream) {
StringBuilder html = new StringBuilder();
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
String s;
while ((s = reader.readLine()) != null) {
html.append(s);
}
} catch (IOException e) {
e.printStackTrace();
}
return html.toString();
}
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what){
case 1:
iHttpConnection.resultGet(msg.obj.toString().trim());
break;
}
return false;
}
});
public interface IHttpConnection{
void resultGet(String html);
}