阿里云(三)

来源:互联网 发布:细川忠兴 知乎 编辑:程序博客网 时间:2024/05/16 17:14

微信申请的是订阅号。

并没有升级为服务号。

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


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

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
原创粉丝点击