📄 weatherservice.java
字号:
/*
* WeatherService.java
*
* Created on 2006年5月5日, 下午9:22
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.j2medev.chapter4.weather;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class WeatherService {
private String host = "http://xml.weather.yahoo.com/forecastrss?";
public WeatherService() {
}
public String getWeather(String location,String style){
try{
URL url = new URL(host+"p="+location+"&u="+style);
InputStream is = url.openStream();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
WeatherHandler handler = new WeatherHandler();
parser.parse(is,handler);
return handler.getWeather();
}catch(MalformedURLException ex){
ex.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}catch(ParserConfigurationException ex){
ex.printStackTrace();
}catch(SAXException ex){
ex.printStackTrace();
}
return null;
}
class WeatherHandler extends DefaultHandler{
Location location = new Location();
Unit unit = new Unit();
Vector v = new Vector();
public String getWeather(){
StringBuffer sb = new StringBuffer();
for(int i = 0;i<v.size();i++){
sb.append(((Forecast)v.get(i)).toString());
}
return location.toString()+sb.toString();
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if("yweather:location".equals(qName)){
for(int i = 0;i<attributes.getLength();i++){
location.set(i,attributes.getValue(i));
}
}else if("yweather:units".equals(qName)){
for(int i = 0;i<attributes.getLength();i++){
unit.set(i,attributes.getValue(i));
}
}else if("yweather:forecast".equals(qName)){
Forecast forecast = new Forecast();
for(int i = 0;i<attributes.getLength();i++){
forecast.set(i,attributes.getValue(i));
}
forecast.setUnit(unit);
v.addElement(forecast);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -