博客
关于我
java 获得天气预报信息
阅读量:155 次
发布时间:2019-02-26

本文共 8233 字,大约阅读时间需要 27 分钟。

Java 实现天气预报功能:从请求到数据解析全解析

一、获取天气预报的方法

在实现天气预报功能时,我们需要通过网络请求获取天气信息。常见的做法是使用 HttpClient 或其他网络库来发送 HTTP 请求,获取目标城市的天气数据。

1. 使用 HttpClient 获取数据

以下是使用 HttpClient 的示例代码:

HttpClient client = new HttpClient();String url = "http://example.com/weather?city=" + URLEncoder.encode(city, "GBK");GetMethod method = new GetMethod(url);int httpstatus = client.executeMethod(method);if (httpstatus == 200) {    // 获取响应内容    String result = method.getResponseBodyAsString();    // 转码为GBK    result = new String(result.getBytes("iso-8859-1"), "GBK");    // 解析响应内容    parseWeatherData(result);}

2. 处理中文编码问题

在发送请求时,城市名需要进行 URL 编码,避免乱码:

String url = "http://example.com/weather?city=" + URLEncoder.encode(city, "GBK");

3. 解析天气数据

天气数据通常以 XML 格式返回。我们需要解析 XML 数据,提取所需的信息,如温度、风速、气压等。

以下是一个简化的解析方法:

public void parseWeatherData(String html) {    // 提取天气信息    String climate = parseWeatherInfo(html, "天气");    String temperature = parseWeatherInfo(html, "气温");    String wind = parseWeatherInfo(html, "风");    String barometric = parseWeatherInfo(html, "气压");        System.out.println("天气:" + climate + "/ 气温 :" + temperature + "/ 风 " + wind + "/ 气压" + barometric);}

4. 解析方法

以下是一个简单的解析方法:

public String parseWeatherInfo(String str, String word) {    String w = null;    String st = "w365line1";    int a = str.indexOf(st);    if (a != -1) {        String div1 = "
"; String div2 = "
"; String keyword = ":"; int d1 = str.lastIndexOf(div1, a); int d2 = str.indexOf(div2, a); if (d2 != -1) { String str2 = str.substring(d1, d2 + div2.length()); if (str2.indexOf(word) != -1) { w = filterStr(str2, word, ""); if (w == null) { w = filterStr(str2, word, "N/A"); } return w; } else { w = parseWeatherInfo(str.substring(0, d2) + div2, word); } } } return w;}

5. 数据过滤方法

以下是一个简单的过滤方法:

public String filterStr(String html, String word, String replacement) {    try {        if (replacement == null) {            replacement = "";        }        String str = html;        String str1 = "(<[^>]*>)|( )";        Pattern p = Pattern.compile(str1);        Matcher m = p.matcher(str);        StringBuffer sb = new StringBuffer();        while (m.find()) {            m.appendReplacement(sb, replacement);        }        m.appendTail(sb);        return sb.toString();    } catch (Exception e) {        return html;    }}

二、完整代码实现

以下是完整的 Java 代码实现:

package stwolf.hustbaidu.java.learn.filelist;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;import java.util.HashMap;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;class GetWeatherInfo {    public static HashMap
cityCode = new HashMap
(); private final String[] dictionaryStrings = { "龙卷风", "热带风暴", "飓风", "强雷阵雨", "雷阵雨", "小雨加雪", "雨加冰雹", "雪加冰雹", "冰雨", "毛毛雨", "冻雨", "阵雨", "阵雨", "小雪", "零星小雪", "高吹雪", "雪", "冰雹", "雨夹雪", "尘", "雾", "薄雾", "多烟的", "大风", "有风", "寒冷", "阴天", "夜间阴天", "白天阴天", "夜间多云", "白天多云", "夜间清亮", "晴朗", "转晴", "转晴", "雨夹冰雹", "热", "雷阵雨", "雷阵雨", "雷阵雨", "雷阵雨", "大雪", "阵雪", "大雪" }; public GetWeatherInfo() { initCitys(); } private void initCitys() { cityCode.put("北京", "0008"); cityCode.put("天津", "0133"); cityCode.put("武汉", "0138"); cityCode.put("杭州", "0044"); cityCode.put("合肥", "0448"); cityCode.put("上海", "0116"); cityCode.put("福州", "0031"); cityCode.put("重庆", "0017"); cityCode.put("南昌", "0097"); cityCode.put("香港", "0049"); cityCode.put("济南", "0064"); cityCode.put("澳门", "0512"); cityCode.put("郑州", "0165"); cityCode.put("呼和浩特", "0249"); cityCode.put("乌鲁木齐", "0135"); cityCode.put("长沙", "0013"); cityCode.put("银川", "0259"); cityCode.put("广州", "0037"); cityCode.put("拉萨", "0080"); cityCode.put("海口", "0502"); cityCode.put("南京", "0100"); cityCode.put("成都", "0016"); cityCode.put("石家庄", "0122"); cityCode.put("贵阳", "0039"); cityCode.put("太原", "0129"); cityCode.put("昆明", "0076"); cityCode.put("沈阳", "0119"); cityCode.put("西安", "0141"); cityCode.put("长春", "0010"); cityCode.put("兰州", "0079"); cityCode.put("西宁", "0236"); } private Document getWeatherXML(String cityCode) throws IOException { URL url = new URL("" + cityCode + "&u=c"); URLConnection connection = url.openConnection(); Document Doc = stringToElement(connection.getInputStream()); return Doc; } private void saveXML(Document Doc, String Path) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer; try { transformer = transFactory.newTransformer(); DOMSource domSource = new DOMSource(Doc); File file = new File(Path); FileOutputStream out = new FileOutputStream(file); StreamResult xmlResult = new StreamResult(out); transformer.transform(domSource, xmlResult); } catch (Exception e) { System.out.println("保存文件出错!"); } } public String getWeather(String city) { String result = null; try { Document doc = getWeatherXML(GetWeatherInfo.cityCode.get(city)); NodeList nodeList = doc.getElementsByTagName("channel"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); NodeList nodeList1 = node.getChildNodes(); for (int j = 0; j < nodeList1.getLength(); j++) { Node node1 = nodeList1.item(j); if (node1.getNodeName().equalsIgnoreCase("item")) { NodeList nodeList2 = node1.getChildNodes(); for (int k = 0; k < nodeList2.getLength(); k++) { Node node2 = nodeList2.item(k); if (node2.getNodeName().equalsIgnoreCase("yweather:forecast")) { NamedNodeMap nodeMap = node2.getAttributes(); Node lowNode = nodeMap.getNamedItem("low"); Node highNode = nodeMap.getNamedItem("high"); Node codeNode = nodeMap.getNamedItem("code"); String day = "今天"; if (result == null) { result = ""; } else { day = "明天"; } result = result + day + " 最低温度:" + lowNode.getNodeValue() + "℃ 最高温度:" + highNode.getNodeValue() + "℃"; } } } } } saveXML(doc, "C:/Users/ygui/Desktop/Weather.xml"); } catch (Exception e) { e.printStackTrace(); } return result; } public Document stringToElement(InputStream input) { try { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(input); return doc; } catch (Exception e) { return null; } } public static void main(String[] args) throws Exception { GetWeatherInfo info = new GetWeatherInfo(); String weather = info.getWeather("武汉"); System.out.println(weather); }}

三、常见问题与解决方案

  • 网络请求超时

    • 解决方案:增加连接超时时间,或者使用多线程请求。
  • 乱码问题

    • 解决方案:确保请求参数和响应内容都正确编码和解码。
  • XML 解析失败

    • 解决方案:检查 XML 格式是否正确,或者使用更灵活的解析方式。
  • 天气数据不完整

    • 解决方案:在解析过程中增加错误处理,确保获取完整的数据。
  • 四、总结

    通过以上方法,我们可以实现从网络请求到数据解析的完整流程,获取所需的天气预报信息。该方法基于标准的 XML 数据格式,结合 HttpClient 和 XML 解析技术,能够灵活适应不同天气服务提供商的 API 接口。

    转载地址:http://gayy.baihongyu.com/

    你可能感兴趣的文章
    Objective-C实现Fedwick树算法(附完整源码)
    查看>>
    Objective-C实现fenwick tree芬威克树算法(附完整源码)
    查看>>
    Objective-C实现FenwickTree芬威克树算法(附完整源码)
    查看>>
    Objective-C实现fft2函数功能(附完整源码)
    查看>>
    Objective-C实现FFT快速傅立叶变换算法(附完整源码)
    查看>>
    Objective-C实现FFT算法(附完整源码)
    查看>>
    Objective-C实现fibonacci search斐波那契查找算法(附完整源码)
    查看>>
    Objective-C实现fibonacci斐波那契算法(附完整源码)
    查看>>
    Objective-C实现FigurateNumber垛积数算法(附完整源码)
    查看>>
    Objective-C实现finding bridges寻找桥梁算法(附完整源码)
    查看>>
    Objective-C实现first come first served先到先得算法(附完整源码)
    查看>>
    Objective-C实现Gale-Shapley盖尔-沙普利算法(附完整源码)
    查看>>
    Objective-C实现getline函数功能(附完整源码)
    查看>>
    Objective-C实现greatest common divisor最大公约数算法(附完整源码)
    查看>>
    Objective-C实现greedy coin change贪心硬币找零算法(附完整源码)
    查看>>
    Objective-C实现half adder半加器算法(附完整源码)
    查看>>
    Objective-C实现hamiltonianCycle哈密尔顿图算法(附完整源码)
    查看>>
    Objective-C实现hamming code汉明码算法(附完整源码)
    查看>>
    Objective-C实现hamming numbers汉明数算法(附完整源码)
    查看>>
    Objective-C实现hammingDistance汉明距离算法(附完整源码)
    查看>>