码迷,mamicode.com
首页 > 微信 > 详细

微信公众平台之超简单实用的天气预报后台实现

时间:2014-11-27 23:42:37      阅读:591      评论:0      收藏:0      [点我收藏+]

标签:微信公众平台天气预报接口   新浪天气预报实现   java   微信   新浪   

微信公众平台之超简单实用的天气预报后台实现


        概述,前段时间我在开发一个自己的微信公众平台,需要实现天气预报功能,在网上度娘了下,实现天气预报的接口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,说明如下:

<Profiles>
<Weather>
<city>广州</city>
<status1>晴</status1>
<status2>晴</status2>
<figure1>qing</figure1>
<figure2>qing</figure2>
<direction1>无持续风向</direction1>
<direction2>无持续风向</direction2>
<power1>≤3</power1>
<power2>≤3</power2>
<temperature1>7</temperature1>
<temperature2>-5</temperature2>
<ssd>0</ssd>
<tgd1>7</tgd1>
<tgd2>7</tgd2>
<zwx>2</zwx>
<ktk>7</ktk>
<pollution>3</pollution>
<xcz></xcz>
<zho></zho>
<diy></diy>
<fas></fas>
<chy>6</chy>
<zho_shuoming>暂无</zho_shuoming>
<diy_shuoming>暂无</diy_shuoming>
<fas_shuoming>暂无</fas_shuoming>
<chy_shuoming>棉衣、冬大衣、皮夹克、内着衬衫或羊毛内衣、毛衣、外罩大衣</chy_shuoming>
<pollution_l>一般</pollution_l>
<zwx_l>弱</zwx_l>
<ssd_l>较凉</ssd_l>
<fas_l>暂无</fas_l>
<zho_l>暂无</zho_l>
<chy_l>薄冬衣</chy_l>
<ktk_l>建议开启(制热)</ktk_l>
<xcz_l>暂无</xcz_l>
<diy_l>暂无</diy_l>
<pollution_s>对空气污染物扩散无明显影响</pollution_s>
<zwx_s>紫外线弱</zwx_s>
<ssd_s>老年、幼儿、体弱者外出需要带上薄围巾、薄手套。</ssd_s>
<ktk_s>建议开启空调</ktk_s>
<xcz_s>暂无</xcz_s>
<gm>2</gm>
<gm_l>易发期</gm_l>
<gm_s>天气很凉,季节转换的气候,慎重增加衣服;较易引起感冒;</gm_s>
<yd>5</yd>
<yd_l>不适宜</yd_l>
<yd_s>虽然晴空万里,但是户外运动时会感到很凉;</yd_s>
<savedate_weather>2013-03-01</savedate_weather>
<savedate_life>2013-03-01</savedate_life>
<savedate_zhishu>2013-03-01</savedate_zhishu>
</Weather>
</Profiles>

标签中1表示白天,2表示夜间

<status>

< figure>

<direction>

<power>

<temperature>

<ssd>

<ssd_l>

<ssd_s>

<tgd>

<zwx>

<zwx_l>

<zwx_s>

<ktk>

<ktk_l>

<ktk_s>

<pollution>

<pollution_l>

<pollution_s>

<xcz>

<xcz_l>

<xcz_s>

<chy>

<chy_l>

<chy_shuoming>

<gm>

<gm_l>

<gm_s>

<yd>

<yd_l>

<yd_s>

<zho>

<zho_l>

<zho_shuoming>

<diy>

<diy_l>

<diy_shuoming>

<fas>

<fas_l>

<fas_shuoming>

<savedate_weather>

<savedate_life>

<savedate_zhishu>

天气情况中文

天气情况拼音

风向

风级

温度

体感指数数值

体感度指数

体感度指数说明

体感温度

紫外线指数数值

紫外线指数

紫外线指数说明

空调指数数值

空调指数


空调指数说明

污染指数数值

污染物扩散条件

污染指数说明

洗车指数数值

洗车指数

洗车指数说明

穿衣指数数值

穿衣指数

穿衣说明

感冒指数数值

感冒指数

感冒指数说明

运动指数数值

运动指数

运动指数说明

天气预报日期

生活日期

指数日期


        实现,下面就贴出我具体实现的代码,虽然返回的是XML,但是我没有使用DOM4J或者XStream进行解析,完全使用简单的正则表达式就搞定了,废话少说,看具体代码:

1、weather服务类

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("广州"));
	}

}

2、http工具类

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;
	}
}

欢迎大家关注小编的微信公众平台:MyGoodHelper,是您出行、生活、学习和娱乐的得力助手,我们一起进步。OK,TKS!

微信公众平台之超简单实用的天气预报后台实现

标签:微信公众平台天气预报接口   新浪天气预报实现   java   微信   新浪   

原文地址:http://blog.csdn.net/lanpiao_87/article/details/41556265

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!