【个人收藏】
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;
}
}
分享到:
相关推荐
throw new Exception($"Failed to get weather data. Status code: {response.StatusCode}"); } } ``` 这段代码定义了一个异步方法,通过传入城市名和API密钥,获取该城市的天气信息。注意,这里我们使用了`async...
throw new Exception($"Failed to get weather data. Status code: {response.StatusCode}"); } } ``` 接下来,获取到的天气数据通常是JSON格式,我们需要解析这个数据。C#提供了多种方式来解析JSON,如Json.NET...
throw new Exception("Failed to get weather data."); } ``` 在用户界面方面,你可能需要使用WPF(Windows Presentation Foundation)或WinForms来创建一个简单的桌面应用。设计一个界面,让用户输入城市名,然后...
throw new Exception("Failed to get weather data."); } ``` 在这个示例中,我们使用了`HttpClient`类发送GET请求,并处理返回的JSON数据。`WeatherData`是自定义的数据模型,用于存储从API获取的天气信息。 接...
throw new Exception($"Failed to get weather data. Status code: {response.StatusCode}"); } } ``` 这段代码定义了一个异步方法`GetWeatherData`,它接受城市名和API密钥作为参数,然后构造一个请求URL,并...
12 Build a Weather App - Use GPS and APIs to Get Data from the Web 1/2
在这个教程“12 Build a Weather App - Use GPS and APIs to Get Data from the Web 2/2”中,我们将深入探讨如何构建一个天气应用程序,利用GPS定位技术和Web APIs获取实时的气象数据。这是一个Java编程项目,重点...
String url = "http://api.openweathermap.org/data/2.5/weather?q=北京&appid=YOUR_API_KEY"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response....
设置 URL 为天气 API 的地址,如 "http://api.openweathermap.org/data/2.5/weather?q=北京&appid=your_api_key",然后在 OnWorkDone 事件中解析返回的 JSON 数据,展示天气情况。 总之,Delphi 控件 HTTPGet 提供...
接着,我们使用`http.get()`发起请求,并在响应对象上监听`data`和`end`事件。当接收到数据时,我们将其累积到`data`字符串中;当所有数据接收完毕后,我们解析JSON响应并打印天气信息。 然而,如果你需要更复杂的...
weather_data = weather_command.get_weather('New York') ``` 5. 查询结果通常会以Python字典或对象的形式返回,你可以解析这些数据来获取温度、湿度、风速等信息: ```python temperature = weather_data['...
weather_data = get_weather_data("Beijing") ``` 在上述代码中,我们定义了一个函数`get_weather_data`,它接受一个城市名作为参数,然后构造一个完整的API请求URL,并发送GET请求。如果服务器返回的状态码为200,...
文件`httpRequest-Get-Weather-Test.js`可能包含上述代码的实现,用于测试这两种方法。请注意替换`YOUR_API_KEY`为实际的API密钥,以确保能正确调用天气API。 总的来说,Node.js的`http`模块提供了强大的功能,让...
def store_data(weather_data): df = pd.DataFrame(weather_data, index=[0]) df.to_csv('weather_data.csv', index=False) ``` 最后,整合以上步骤,创建一个主程序来运行整个爬虫流程: ```python if __name__...
Write-Host "Failed to retrieve weather data: $_" } ``` 这个例子展示了如何获取指定城市的温度和天气描述,然后你可以根据BlueIris的具体接口,将这些信息写入到Overlay中。 总的来说,通过Powershell和...
def get_weather_data(self): # 发送HTTP请求并返回数据 pass def parse_weather_data(self, raw_data): # 解析数据并存储在类属性中 pass def display_weather(self): # 显示天气信息 pass ``` 至于...
"description": data['weather'][0]['description'], "humidity": data['main']['humidity'] } else: raise Exception("Failed to get weather info") ``` 最后,压缩包中的`weather`文件可能包含了实现以上...
def get_weather_data(api_key, location): url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}" response = requests.get(url) return response.json() ``` 2. **数据解析*...
天气的API(Taiwan weather data API): 台湾地图SVG素材(Taiwan Map SVG): 参考的教学(Referencing Tutorials): (不包含API串接&Axios) 尝试使用的技术 基础技术:HTML+CSS 进阶技术:SVG的操作+SCSS+JQUARY+...
weather_desc = weather_data["weather"][0]["description"] print(f"城市: {city}") print(f"温度: {temperature:.2f}℃") print(f"气压: {pressure} hPa") print(f"湿度: {humidity}%") print(f"天气状况:...