调用天气接口

本文介绍了一个使用Java实现的天气查询工具类,通过调用WebXML的天气预报WebService接口,能够获取并解析特定城市的天气信息。该工具类利用SOAP1.1格式发送请求,接收XML响应并解析关键天气数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//class

package cn.jun.untils;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

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

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class WeatherUtil {
    
    /**
    * 对服务器端返回的XML文件流进行解析
    * 
    * @param city 用户输入的城市名称
    * @return          字符串 用#分割
    */
    public String getWeather(String city) {
        try {
            //使用Dom解析
            Document doc;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            //获取调用接口后返回的流
            InputStream is = getSoapInputStream(city);
            doc = db.parse(is);
            //xml的元素标签是"<string>值1</string><string>值2</string>……"
            NodeList nl = doc.getElementsByTagName("string");
            StringBuffer sb = new StringBuffer();
            for (int count = 0; count < nl.getLength(); count++) {
                Node n = nl.item(count);
                if(n.getFirstChild().getNodeValue().equals("查询结果为空!")) {
                    sb = new StringBuffer("#") ;
                    break ;
                }
                //解析并以"#"为分隔符,拼接返回结果
                sb.append(n.getFirstChild().getNodeValue() + "#");
            }
            is.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /*
    * 用户把SOAP请求发送给服务器端,并返回服务器点返回的输入流
    * 
    * @param city  用户输入的城市名称
    * @return 服务器端返回的输入流,供客户端读取
    * @throws Exception
    * @备注:有四种请求头格式1、SOAP 1.1;  2、SOAP 1.2 ; 3、HTTP GET; 4、HTTP POST
    * 参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
    */
    private InputStream getSoapInputStream(String city) throws Exception {
        try {
        //获取请求规范
        String soap = getSoapRequest(city);
        if (soap == null) {
        return null;
        }
        //调用的天气预报webserviceURL
        URL url = new URL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx");
        URLConnection conn = url.openConnection();
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
        conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        //调用的接口方法是“getWeatherbyCityName”
        conn.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName");
        OutputStream os = conn.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");
        osw.write(soap);
        osw.flush();
        osw.close();
        //获取webserivce返回的流
        InputStream is = conn.getInputStream();
        return is;
        } catch (Exception e) {
        e.printStackTrace();
        return null;
        }
    }
    
    /*
    * 获取SOAP的请求头,并替换其中的标志符号为用户输入的城市
    * 
    * @param city: 用户输入的城市名称
    * @return              客户将要发送给服务器的SOAP请求规范
    * @备注:有四种请求头格式1、SOAP 1.1;  2、SOAP 1.2 ; 3、HTTP GET; 4、HTTP POST
    * 参考---》http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?op=getWeatherbyCityName
    * 本文采用:SOAP 1.1格式
    */
    private String getSoapRequest(String city) {
        StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
            + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
            + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
            + "<soap:Body><getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">"
            + "<theCityName>"
            + city
            + "</theCityName></getWeatherbyCityName>"
            + "</soap:Body></soap:Envelope>");
            return sb.toString();
        }
    
    //测试
    @Test
    public void test(){
        //new WeatherUtil().getWeather("贵阳");
        //System.out.println(new WeatherUtil().getWeather("贵阳").toString());
        
        WeatherUtil weath=new WeatherUtil();
        
        //查看城市:贵阳
        String weather=weath.getWeather("贵阳");
        String len[]=weather.split("#");
        for(int i=0;i<len.length-1;i++){
            System.out.println(len[i]);
        }

    System.out.println("================");
        System.out.println("城市:"+len[1]);
        System.out.println("天气:"+len[5]);
    }
}

//================================result

贵州
贵阳
57816
57816.jpg
2018/11/12 15:24:51
10℃/14℃
11月12日 阴
东北风转东风小于3级
2.gif
2.gif
今日天气实况:气温:10℃;风向/风力:北风 2级;湿度:89%;紫外线强度:最弱。空气质量:较差。
紫外线指数:最弱,辐射弱,涂擦SPF8-12防晒护肤品。
健臻·血糖指数:不易波动,天气条件好,血糖不易波动,可适时进行户外锻炼。
穿衣指数:较冷,建议着厚外套加毛衣等服装。
洗车指数:较适宜,无雨且风力较小,易保持清洁度。
空气污染指数:较差,气象条件较不利于空气污染物扩散。。

11℃/15℃
11月13日 小雨
东南风转南风小于3级
7.gif
7.gif
11℃/19℃
11月14日 小雨转中雨
南风转北风小于3级
7.gif
8.gif

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值