`
xwl1991
  • 浏览: 13635 次
  • 性别: Icon_minigender_1
  • 来自: 湖南
最近访客 更多访客>>
社区版块
存档分类
最新评论

Get Weather data

阅读更多
【个人收藏】
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;
	}
}
分享到:
评论

相关推荐

    C# 获取各个城市天气信息

    throw new Exception($"Failed to get weather data. Status code: {response.StatusCode}"); } } ``` 这段代码定义了一个异步方法,通过传入城市名和API密钥,获取该城市的天气信息。注意,这里我们使用了`async...

    天气预报 C#

    throw new Exception($"Failed to get weather data. Status code: {response.StatusCode}"); } } ``` 接下来,获取到的天气数据通常是JSON格式,我们需要解析这个数据。C#提供了多种方式来解析JSON,如Json.NET...

    C#天气查询

    throw new Exception("Failed to get weather data."); } ``` 在用户界面方面,你可能需要使用WPF(Windows Presentation Foundation)或WinForms来创建一个简单的桌面应用。设计一个界面,让用户输入城市名,然后...

    .NET获取不同地区的天气预报和外网IP地址

    throw new Exception("Failed to get weather data."); } ``` 在这个示例中,我们使用了`HttpClient`类发送GET请求,并处理返回的JSON数据。`WeatherData`是自定义的数据模型,用于存储从API获取的天气信息。 接...

    C#制作天气预报(根据城市不同动态得获得天气预报)

    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 1/2

    12 Build a Weather App - Use GPS and APIs to Get Data from the Web 2/2

    在这个教程“12 Build a Weather App - Use GPS and APIs to Get Data from the Web 2/2”中,我们将深入探讨如何构建一个天气应用程序,利用GPS定位技术和Web APIs获取实时的气象数据。这是一个Java编程项目,重点...

    Android 解析Google Weather API

    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....

    Delphi控件 HTTPGet

    设置 URL 为天气 API 的地址,如 "http://api.openweathermap.org/data/2.5/weather?q=北京&appid=your_api_key",然后在 OnWorkDone 事件中解析返回的 JSON 数据,展示天气情况。 总之,Delphi 控件 HTTPGet 提供...

    通过NodeJS中的http.get() 和 http.request()模块两种方法,调用中国天气api

    接着,我们使用`http.get()`发起请求,并在响应对象上监听`data`和`end`事件。当接收到数据时,我们将其累积到`data`字符串中;当所有数据接收完毕后,我们解析JSON响应并打印天气信息。 然而,如果你需要更复杂的...

    Python库 | weather_command-0.4.1-py3-none-any.whl

    weather_data = weather_command.get_weather('New York') ``` 5. 查询结果通常会以Python字典或对象的形式返回,你可以解析这些数据来获取温度、湿度、风速等信息: ```python temperature = weather_data['...

    python天气查询

    weather_data = get_weather_data("Beijing") ``` 在上述代码中,我们定义了一个函数`get_weather_data`,它接受一个城市名作为参数,然后构造一个完整的API请求URL,并发送GET请求。如果服务器返回的状态码为200,...

    通过NodeJS中的http.get 和 http.request模块两种方法,调用中国天气api

    文件`httpRequest-Get-Weather-Test.js`可能包含上述代码的实现,用于测试这两种方法。请注意替换`YOUR_API_KEY`为实际的API密钥,以确保能正确调用天气API。 总的来说,Node.js的`http`模块提供了强大的功能,让...

    爬取天气信息的Python爬虫完整实现代码.rar

    def store_data(weather_data): df = pd.DataFrame(weather_data, index=[0]) df.to_csv('weather_data.csv', index=False) ``` 最后,整合以上步骤,创建一个主程序来运行整个爬虫流程: ```python if __name__...

    java 通过get请求访问api得到天气预报相关的json串

    首先,我们需要发送一个GET请求到指定的URL(例如:"http://m.weather.com.cn/data5/city.xml")来获取省份数据。这可以通过使用Apache HttpClient库中的`HttpClient`和`GetMethod`类实现。在`getCityCode`方法中,...

    Get-Weather:获取BlueIris Overlay的OpenWeather信息

    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`文件可能包含了实现以上...

    Weather Forecast App in Python with Source Code.zip

    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. **数据解析*...

    Taiwan_Weather_Map:台湾_天气_地图

    天气的API(Taiwan weather data API): 台湾地图SVG素材(Taiwan Map SVG): 参考的教学(Referencing Tutorials): (不包含API串接&Axios) 尝试使用的技术 基础技术:HTML+CSS 进阶技术:SVG的操作+SCSS+JQUARY+...

Global site tag (gtag.js) - Google Analytics