Get Weather data

本文介绍了一个用于获取中国各城市天气信息的Java程序。该程序通过解析Web服务返回的XML数据来获取地区、省份、城市的代码,并进一步查询指定城市的天气状况。
【个人收藏】
package com.weather;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class WeatherUtil {
private static String SERVICES_HOST = "www.webxml.com.cn";
private static String WEATHER_SERVICES_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/";
private static String PROVINCE_CODE_URL = WEATHER_SERVICES_URL + "getRegionProvince";
private static String CITY_CODE_URL = WEATHER_SERVICES_URL + "getSupportCityString?theRegionCode=";
private static String WEATHER_QUERY_URL = WEATHER_SERVICES_URL + "getWeather?theUserID=&theCityCode=";

private final static String COUNTRY_CODE_URL=WEATHER_SERVICES_URL+"getRegionCountry";

private WeatherUtil() {
}

public static void main(String[] args) {
int RegionCountry =getRegionCountry("");
int provinceCode = getProvinceCode("广东"); // 3119
int cityCode = getCityCode(provinceCode, "深圳"); // 974
List<String> weatherList = getWeather(cityCode);
for (String weather : weatherList) {
System.out.println(weather);
}
}

public static int getRegionCountry(String provinceCountryName){
Document document;
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
int provinceCode=0;
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
InputStream is = getSoapInputStream(COUNTRY_CODE_URL);
document = db.parse(is);
NodeList nodeList = document.getElementsByTagName("string");
int length = nodeList.getLength();
for (int i=0; i < length; i++) {
Node n = nodeList.item(i);
String result = n.getFirstChild().getNodeValue();
String[] address = result.split(",");
String pName = address[0];
String pCode = address[1];
if (pName.equalsIgnoreCase(provinceCountryName)) {
provinceCode = Integer.parseInt(pCode);
}
}
} catch (DOMException e){
// TODO Auto-generated catch block
System.out.println("Document Exception "+e.toString());
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
System.out.println("Parse Configuration Exception "+e.toString());
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
System.out.println("SAX Exception "+e.toString());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IO Exception "+e.toString());
e.printStackTrace();
}
return provinceCode;
}

public static int getProvinceCode(String provinceName) {
Document document;
DocumentBuilderFactory documentBF = DocumentBuilderFactory
.newInstance();
documentBF.setNamespaceAware(true);
int provinceCode = 0;
try {
DocumentBuilder documentB = documentBF.newDocumentBuilder();
InputStream inputStream = getSoapInputStream(PROVINCE_CODE_URL);
document = documentB.parse(inputStream);
NodeList nodeList = document.getElementsByTagName("string");
int len = nodeList.getLength();
for (int i = 0; i < len; i++) {
Node n = nodeList.item(i);
String result = n.getFirstChild().getNodeValue();
String[] address = result.split(",");
String pName = address[0];
String pCode = address[1];
if (pName.equalsIgnoreCase(provinceName)) {
provinceCode = Integer.parseInt(pCode);
}
}
inputStream.close();
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return provinceCode;
}

public static int getCityCode(int provinceCode, String cityName) {
Document doc;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
int cityCode = 0;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = getSoapInputStream(CITY_CODE_URL + provinceCode);
doc = db.parse(is);
NodeList nl = doc.getElementsByTagName("string");
int len = nl.getLength();
for (int i = 0; i < len; i++) {
Node n = nl.item(i);
String result = n.getFirstChild().getNodeValue();
String[] address = result.split(",");
String cName = address[0];
String cCode = address[1];
if (cName.equalsIgnoreCase(cityName)) {
cityCode = Integer.parseInt(cCode);
}
}
is.close();
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return cityCode;
}

public static InputStream getSoapInputStream(String url) {
InputStream inputStream = null;
try {
URL urlObj = new URL(url);
URLConnection urlConn = urlObj.openConnection();
urlConn.setRequestProperty("Host", SERVICES_HOST);
urlConn.connect();
inputStream = urlConn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}

public static List<String> getWeather(int cityCode) {
List<String> weatherList = new ArrayList<String>();
Document document;
DocumentBuilderFactory documentBF = DocumentBuilderFactory
.newInstance();
documentBF.setNamespaceAware(true);
try {
DocumentBuilder documentB = documentBF.newDocumentBuilder();
InputStream inputStream = getSoapInputStream(WEATHER_QUERY_URL + cityCode);
document = documentB.parse(inputStream);
NodeList nl = document.getElementsByTagName("string");
int len = nl.getLength();
for (int i = 0; i < len; i++) {
Node n = nl.item(i);
String weather = n.getFirstChild().getNodeValue();
weatherList.add(weather);
}
inputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DOMException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return weatherList;
}
}
class WeatherBroadcastRequest(BaseModel): key: str # 只允许 'current' 或 'future' city_code: Optional[str] = DEFAULT_WEATHER_CITY_CODE # 城市代码,可选,默认440305 class WeatherLiveData(BaseModel): humidity: str temperature: str weather: str winddirection: str windpower: str class WeatherForecastData(BaseModel): date: str temphigh: str templow: str weather: str # 响应数据模型 class WeatherBroadcastData(BaseModel): lives: List[WeatherLiveData] forecast: List[WeatherForecastData] @app.post("/api/web/weather_broadcast", response_model=WeatherBroadcastData) async def weather_broadcast(data: WeatherBroadcastRequest): try: # Validate input parameters if data.key not in WEATHER_KEY_MAP: #raise HTTPException(status_code=400, detail="key字段只允许 'current' 或 'future'") return {"code":400,"msg": "key字段只允许 'current' 或 'future'"} # Check if WebHelper is initialized if web_helper is None: #raise HTTPException(status_code=500, detail="Weather service not initialized") return {"code":500,"msg": "Weather service not initialized"} city_code = data.city_code if data.city_code else DEFAULT_WEATHER_CITY_CODE is_current = data.key == 'current' try: # Get weather data from WebHelper weather_response = web_helper.request_weather(is_current, city_code) if weather_response.status_code != 200: #raise HTTPException(status_code=502, detail=f"Weather API returned error: {weather_response.status_code}") return {"code":502,"msg":f"Weather API returned error: {weather_response.status_code}"} weather_data = weather_response.json() # Check if the weather API response is valid if weather_data.get('status') != '1' or weather_data.get('infocode') != "10000": error_msg = weather_data.get('info', 'Unknown weather API error') #raise HTTPException(status_code=503, detail=f"Weather API error: {error_msg}") return {"code":503,"msg":f"Weather API error: {error_msg}"} # Parse weather data based on type if is_current: # Parse current weather data lives_data = weather_data.get('lives', []) if not lives_data: #raise HTTPException(status_code=503, detail="No current weather data available") return {"code":503,"msg":"No current weather data available"} live_weather = lives_data[0] weather_lives = [WeatherLiveData( humidity=live_weather.get('humidity', ''), temperature=live_weather.get('temperature', ''), weather=live_weather.get('weather', ''), winddirection=live_weather.get('winddirection', ''), windpower=live_weather.get('windpower', '') )] weather_forecasts = [] else: # Parse forecast weather data forecasts_data = weather_data.get('forecasts', []) if not forecasts_data or not forecasts_data[0].get('casts'): #raise HTTPException(status_code=503, detail="No weather forecast data available") return {"code":503,"msg":"No weather forecast data available"} weather_lives = [] weather_forecasts = [] for cast in forecasts_data[0]['casts']: weather_forecasts.append(WeatherForecastData( date=cast.get('date', ''), temphigh=cast.get('daytemp', ''), templow=cast.get('nighttemp', ''), weather=cast.get('dayweather', '') )) # Create response data response_data = WeatherBroadcastData( lives=weather_lives, forecast=weather_forecasts ) # 构造发送给 Brain Agent 的数据 weather_task = { 'agent_name': 'AmusementAgent', 'arguments': { 'type': '天气', 'key': WEATHER_KEY_MAP[data.key], 'city': city_code } } # Send to Brain Agent (failing to send is not considered an error for now) send_success = send_to_brain_agent(weather_task) if send_success: print("[WeatherAPI] Weather data sent to Brain Agent successfully") else: print("[WeatherAPI] Failed to send weather data to Brain Agent") # TODO: In the future, this could be treated as an error: # raise HTTPException(status_code=500, detail="Failed to notify Brain Agent") return response_data except HTTPException: # Re-raise HTTP exceptions as they already have proper status codes raise except Exception as e: print(f"[WeatherAPI] Weather service error: {e}") #raise HTTPException(status_code=503, detail=f"Weather service error: {str(e)}") return {"code":503,"msg":f"Weather service error: {str(e)}"} except HTTPException: # Re-raise HTTP exceptions raise except Exception as e: # Handle any other unexpected errors print(f"[WeatherAPI] Unexpected error: {e}") #raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}") return {"code":503,"msg":f"Weather API error: {e}"} 代码修改,要求①运用继承方法②修改格式如下{ "code": 200, "msg": "xxx", "data": { "xxx": xxx, } }
最新发布
08-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值