欢迎使用优快云-markdown编辑器

,前段时间我在开发一个自己的微信公众平台,需要实现天气预报功能,在网上度娘了下,实现天气预报的接口API还蛮多的,有:中国气象局、雅虎和新浪等,中国天气预报接口需要全国的编码,雅虎的有时候访问不了,研究了下还是新浪提供的接口比较简单实用。新浪天气预报API的URL是http://PHP.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0。其中,city后的城市转码。Password固定,Day为0表示当天天气,1表示第二天的天气,2表示第三天的天气,以此类推,最大为4。返回的XML,

package com.mghs.util;  

import java.io.BufferedReader;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.UnsupportedEncodingException;  
import java.net.HttpURLConnection;  
import java.net.URL;  

/** 
 * Http请求工具类 
 * @author lanp 
 * @since 2014-8-24 13:30:56 
 * @version v1.0.1 
 */  
public class HttpRequestUtil {  

    /** 
     * 编码 
     * @param source 
     * @return 
     */  
    public static String urlEncode(String source,String encode) {  
        String result = source;  
        try {  
            result = java.net.URLEncoder.encode(source,encode);  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
            return "0";  
        }  
        return result;  
    }  

    /** 
     * 发起http请求获取返回结果 
     * @param requestUrl 请求地址 
     * @return 
     */  
    public static String httpRequest(String requestUrl) {  
        StringBuffer buffer = new StringBuffer();  
        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  

            httpUrlConn.setDoOutput(false);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  

            httpUrlConn.setRequestMethod("GET");  
            httpUrlConn.connect();  

            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  

            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  

        } catch (Exception e) {  
            System.out.println(e.getStackTrace());  
        }  
        return buffer.toString();  
    }  

    /** 
     * 发送http请求取得返回的输入流 
     * @param requestUrl 请求地址 
     * @return InputStream 
     */  
    public static InputStream httpRequestIO(String requestUrl) {  
        InputStream inputStream = null;  
        try {  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setRequestMethod("GET");  
            httpUrlConn.connect();  
            // 获得返回的输入流  
            inputStream = httpUrlConn.getInputStream();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return inputStream;  
    }  
}  
[java] view plain copy print?
package com.mghs.service;  

import java.io.UnsupportedEncodingException;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  

import com.mghs.util.GetAppConfUtil;  
import com.mghs.util.HttpRequestUtil;  

/** 
 * 天气预报服务 
 * @author lanp 
 * @since 2014-7-29 20:56:16 
 * @version v1.0.1 
 */  
public class WeatherService {  


    /** 
     * GBK编码 
     * @param source 
     * @return 
     */  
    public static String urlEncodeGBK(String source) {  
        String result = source;  
        try {  
            result = java.net.URLEncoder.encode(source, "GBK");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  

    /** 
     * 获取天气预报XML信息并返回 
     * @param source 
     * @return 
     */  
    public static String getWeatherXml(String source,int day) {  
        String dst = null;  
        // 组装查询地址  
        String requestUrl = "http://php.weather.sina.com.cn/xml.php?city={keyWord}&password=DJOYnieT8234jlsK&day="+day;  
        // 对参数q的值进行urlEncode utf-8编码  
        requestUrl = requestUrl.replace("{keyWord}", HttpRequestUtil.urlEncode(source, "GBK"));  
        dst = HttpRequestUtil.httpRequest(requestUrl);  
        return dst;  
    }  

    /** 
     * 获取今天、明天和后天的天气预报信息并返回 
     * @param source 
     * @return 
     */  
    public static String getWeatherInfo(String source) {  
        StringBuffer buffer = new StringBuffer();  
        buffer.append(source).append(" 今明后三天天气情况如下:\n\n");  
        for(int i=0;i<3;i++) {  
            String weatherXml = getWeatherXml(source,i);  
            if(null==weatherXml || "".equals(weatherXml))  
                return "";  
            String status1 = "";  
            String direction1 = "";  
            String temperature1 = "";  
            String temperature2 = "";   
            String savedate_weather = "";  
            String ssd_l = "";  
            String yd_s = "";  
            Pattern p = Pattern.compile("(.*)(<status1>)(.*?)(</status1>)(.*)");  
            Matcher m = p.matcher(weatherXml);  
            if(m.matches())  
                status1 = m.group(3);  
            if(null==status1 || "".endsWith(status1))  
                return "";  
            p = Pattern.compile("(.*)(<direction1>)(.*?)(</direction1>)(.*)");  
            m = p.matcher(weatherXml);  
            if(m.matches())  
                direction1 = m.group(3);  
            p = Pattern.compile("(.*)(<temperature1>)(.*?)(</temperature1>)(.*)");  
            m = p.matcher(weatherXml);  
            if(m.matches())  
                temperature1 = m.group(3);  
            p = Pattern.compile("(.*)(<temperature2>)(.*?)(</temperature2>)(.*)");  
            m = p.matcher(weatherXml);  
            if(m.matches())  
                temperature2 = m.group(3);  
            p = Pattern.compile("(.*)(<savedate_weather>)(.*?)(</savedate_weather>)(.*)");  
            m = p.matcher(weatherXml);  
            if(m.matches())  
                savedate_weather = m.group(3);  
            p = Pattern.compile("(.*)(<ssd_l>)(.*?)(</ssd_l>)(.*)");  
            m = p.matcher(weatherXml);  
            if(m.matches())  
                ssd_l = m.group(3);  
            p = Pattern.compile("(.*)(<yd_s>)(.*?)(</yd_s>)(.*)");  
            m = p.matcher(weatherXml);  
            if(m.matches())  
                yd_s = m.group(3);  
            buffer.append(savedate_weather).append("\n").append(status1).append(" ").append(direction1).append(" ").append(temperature2)  
                .append("°-").append(temperature1).append("° ").append(ssd_l).append("\n").append("温馨提示:").append(yd_s).append("\n\n");  
        }  
        return (null==buffer?"":buffer.toString());  
    }  

    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        System.out.println(getWeatherInfo("广州"));  
    }  

}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值