微信公众号开发--天气预报(Java版)

转载自:
http://www.codeweblog.com/微信公众平台整合百度天气api/
访问我的个人博客 秋码个人博客
首先需要到百度地图API上申请一个专用key,申请链接为
http://lbsyun.baidu.com/apiconsole/key
微信公众号开发--天气预报(Java版)_第1张图片
然后创建一个用于请求天气API的类。

package com.zhenqi.weather;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import com.google.gson.Gson;
import com.zhenqi.entity.Results;
import com.zhenqi.entity.Status;
import com.zhenqi.entity.Weather;

public class BaiDuWeather {
	private static String api = "http://api.map.baidu.com/telematics/v3/weather?";
	private static String output = "json";
	private static String ak = "你前面百度地图API上申请的key";

	public static String getSend(String str) {
		// 将传进来的城市转码
		try {
			str = URLEncoder.encode(str, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 拼接url
		StringBuffer buf = new StringBuffer();
		buf.append("location=");
		buf.append(str);
		buf.append("&output=");
		buf.append(output);
		buf.append("&ak=");
		buf.append(ak);
		String param = buf.toString();
		// 这是接收百度API返回的内容
		String result = "";
		String urlName = api + param;
		URL realUrl;
		try {
			realUrl = new URL(urlName);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			conn.setDoInput(true);
			BufferedReader br = new BufferedReader(new InputStreamReader(
					conn.getInputStream(),"UTF-8"));

			String line = br.readLine();
			while (line != null) {
				result += line;
				line = br.readLine();
			}
			br.close();
			Gson gson = new Gson();
			Status status = gson.fromJson(result, Status.class);
			List results=status.getResults();
			StringBuffer bf=new StringBuffer();
			for(int i=0;i weather_data=res.getWeather_data();
				for(int j=0;j

我们请求返回的json数据封装在Javabean对象里。
Weather.java

package com.zhenqi.entity;

public class Weather {
	
	private String date;
    private String dayPictureUrl;
    private String nightPictureUrl;
    private String weather;
    private String wind;
    private String temperature;
	//由于篇幅,省略set/get方法,可以使用IDE自动生成它们
}

Results.java

package com.zhenqi.entity;
import java.util.List;

public class Results {
	
	private String currentCity;
    private List weather_data;
    //由于篇幅,省略set/get方法,可以使用IDE自动生成它们
}

Status.java

package com.zhenqi.entity;

import java.util.List;

public class Status{
    private String error;
    private String status;
    private String date;
    private List results;
    //由于篇幅,省略set/get方法,可以使用IDE自动生成它们
}

而后微信请求消息的servlet中添加如下代码:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

    	req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        try {
            Map map = MessageUtil.xmlToMap(req);
            String toUserName = map.get("ToUserName");
            String fromUserName = map.get("FromUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");    

            String message = null;
            //MessageUtil.MESSAGE_TEXT就是 text
            if(MessageUtil.MESSAGE_TEXT.equals(msgType)){
            	if(content.endsWith("天气")){
            		String keyWord = content.replaceAll("天气", "").trim();
        
            		message = MessageUtil.initText(toUserName, fromUserName,BaiDuWeather.getSend(keyWord));
            	}
            }
            out.print(message);
          }catch (Exception e) {
            // TODO: handle exception,
        	e.printStackTrace();
            out.close();
        }  
      }

实现效果如下:
微信公众号开发--天气预报(Java版)_第2张图片
扫描下方二维码进行关注。或 微信公众号搜索 你我杂志刊
微信公众号开发--天气预报(Java版)_第3张图片

你可能感兴趣的:(微信公众号)