阿里云(三)

微信申请的是订阅号。

并没有升级为服务号。

先开发的功能是天气查询,因为这个较简单,容易上手。


先是查询的接口:中国天气网

http://www.weather.com.cn/data/cityinfo/101010100.html

返回的数据

{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"22℃","temp2":"33℃","weather":"晴","img1":"n0.gif","img2":"d0.gif","ptime":"18:00"}}

网址中101010100是城市代码。


在已搭建好的网站中,写好接收微信传递来的用户信息

初步判断为,包含天气和城市名字,比如:北京天气,或者天气北京

这样,根据“天气”调用查询天气的功能

if (keyword.indexOf("天气") >= 0) {
			String city_name = keyword.replace("天气", "");
			content = util.getWeatherInfo(dataAccess, city_name);
			resultStr = textTmpl.format(textTmpl, fromUsername, toUsername,time, content);
		}

public String getWeatherInfo(IDataAccess dataAccess,String city_name){
		String weather="";
		String weather_url="http://www.weather.com.cn/data/cityinfo/";
		String sql="select city_code from city_code_info where city_name='"+city_name+"'";
		String city_code=dataAccess.queryForString(sql, null);
		try {
			String url_str=weather_url+city_code+".html";
			HttpGet httpGet=new HttpGet(url_str);
			HttpResponse httpResponse=new DefaultHttpClient().execute(httpGet);
			if(httpResponse.getStatusLine().getStatusCode()==200){
				String json_weather_str=EntityUtils.toString(httpResponse.getEntity());
				JSONObject json_weather=JSONObject.fromObject(json_weather_str).getJSONObject("weatherinfo");
				String temp1=json_weather.getString("temp1");
				String temp2=json_weather.getString("temp2");
				String weather_info=json_weather.getString("weather");
				String time=json_weather.getString("ptime");
				weather=city_name+":"+temp1+"~"+temp2+" "+weather_info+" "+time+"发布";
			}else{
				weather="暂时无天气信息,请稍后查询";
			}
			return weather;
		} catch (MalformedURLException e) {
			weather="暂时无天气信息,请稍后查询";
			return weather;
		}catch (IOException e) {
			weather="暂时无天气信息,请稍后查询";
			return weather;
		}
	}


对接口返回的JSON数据进行解析,把要显示个用户的数据进行整合。


其中,对于微信传来的用户数据,是xml格式的,在解析时,要注意:

这个xml数据是放在request的body里面,而不是Parameter里面

在获取数据流的时候要转换编码为UTF-8,

request.setCharacterEncoding("UTF-8");
仅这样设置的是无效的,至少我是如此,依旧乱码。

reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));

这样对输入流进行编码后,正常显示,

当回传给微信服务器的时候,对response也要进行编码格式指定

response.setCharacterEncoding("UTF-8");

最后,当用户在订阅号,发送消息时,就会自动回复天气信息。

用的网页版微信,方便截图


这样,一个查询天气的简单公众号功能就实现了。

下面,就是试着去做一个查询公交实时到站信息的功能。


To be continue。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值